我有一个类似于以下示例的数据框:
sample = {'col1': [50.6, 30.67, 40.5, 0, 0, 0],
'col2': [40.74, 30.33, 41.00, 0, 0, 0]}
df_sample = pd.DataFrame(sample)
现在,在这两个col2
与col3
然而,条目代表两个不同的值。例如,对于entry 50.6
,表示val1 = 5
和val2 = 0.6
。另一个例子是41.00
。此值表示4
和1.0
。
基本上,我要获取的是可以按如下方式计算的列:
df_sample['res'] = df_sample.apply(lambda x:
((x['col2']//10)*(x['col2']%10) + (x['col3']//10)*(x['col3']%10))
/ (x['col2']//10 + x['col3']//10), axis=1)
df_sample.fillna(0)
基本上,它是从每列中获得的值获得加权平均值。现在,我想做的是扩展此方法以使用20个列,而无需对DataFrame中的每个列名称进行硬编码。请指教。
您可以省略apply
,而可以使用Series
(的列Dataframes
):
sample = {'col2': [50.6, 30.67, 40.5, 0, 0, 0],
'col3': [40.74, 30.33, 41.00, 0, 0, 0],
'col4': [70.6, 80.67, 70.5, 0, 0, 0],
'col5': [10.74, 50.33, 51.00, 0, 0, 0]}
df_sample = pd.DataFrame(sample)
print (df_sample)
col2 col3 col4 col5
0 50.60 40.74 70.60 10.74
1 30.67 30.33 80.67 50.33
2 40.50 41.00 70.50 51.00
3 0.00 0.00 0.00 0.00
4 0.00 0.00 0.00 0.00
5 0.00 0.00 0.00 0.00
我认为您需要:
print ((((df_sample['col2']//10 * df_sample['col2']%10) +
(df_sample['col3']//10 * df_sample['col3']%10) +
(df_sample['col4']//10 * df_sample['col4']%10) +
(df_sample['col5']//10 * df_sample['col5']%10))
/ (df_sample['col2']//10 + df_sample['col3']//10 +
df_sample['col4']//10 + df_sample['col5']//10)).fillna(0))
0 0.641176
1 0.526842
2 0.725000
3 0.000000
4 0.000000
5 0.000000
dtype: float64
print (((df_sample//10 * df_sample%10).sum(axis=1).div((df_sample//10).sum(axis=1)))
.fillna(0))
0 0.641176
1 0.526842
2 0.725000
3 0.000000
4 0.000000
5 0.000000
dtype: float64
时间:
In [114]: %timeit ((((df_sample['col2']//10 * df_sample['col2']%10) + (df_sample['col3']//10 * df_sample['col3']%10) + (df_sample['col4']//10 * df_sample['col4']%10) + (df_sample['col5']//10 * df_sample['col5']%10)) / (df_sample['col2']//10 + df_sample['col3']//10 + df_sample['col4']//10 + df_sample['col5']//10)).fillna(0))
100 loops, best of 3: 2.03 ms per loop
In [115]: %timeit (((df_sample//10 * df_sample%10).sum(axis=1).div((df_sample//10).sum(axis=1))).fillna(0))
1000 loops, best of 3: 897 µs per loop
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句