我有一个数据框如下:
country_code count_date confirmed_cases growth_rate
0 AFG 2020-09-18 38872.0 94.019934
1 AFG 2020-09-17 38855.0 83.641975
2 AFG 2020-09-16 38815.0 108.154506
3 AFG 2020-09-15 38772.0 196.296296
4 AFG 2020-09-14 38716.0 196.894410
... ... ... ... ...
20451 ZWE 2020-06-03 206.0 NaN
20452 ZWE 2020-06-02 203.0 NaN
20453 ZWE 2020-06-01 178.0 NaN
20454 ZWE 2020-05-31 174.0 NaN
20455 ZWE 2020-05-30 149.0 NaN
我正在尝试这样做: df.groupby('count_date').growth_rate.transform(lambda x: x/x.max())
但是有些x.max()
值是无穷大,在这种情况下,我想使用第二大值。如何将下面的伪代码转换为实际代码:
df.groupby('count_date').growth_rate.transform(lambda x: x/x.max() if x.max() != inf else x/<2nd largest>)
您可以使用遮罩从x删除inf值:
df.groupby('count_date').growth_rate.transform(lambda x: x/x[~np.isinf(x)].max())
这是一个例子:
# Sample DataFrame
df = pd.DataFrame({
'count_date': ['2020-09-17', '2020-09-17', '2020-09-17', '2020-09-17'],
'growth_rate': [ 1, 3, 2, np.inf]
})
df.groupby('count_date').growth_rate.transform(lambda x: x/x[~np.isinf(x)].max())
0 0.333333
1 1.000000
2 0.666667
3 inf
如您所见,缩放是使用x中找到的最大非无限值执行的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句