python - 高效处理 pandas 组
问题描述
我有一个数据框 df,其中包含 a、b、c、d 和 e 列。我想要的是,根据 a、b 和 c 按 df 分组。然后对于每个组,我想删除列 d 和 e 的 NULL 值,该列的值是该组中该列的最频繁值。然后最后删除每个组的重复项。
我正在做以下处理:
final_df = pd.DataFrame()
grouped = df.groupby(['a', 'b', 'c'])
for _, group in grouped:
group = group.replace('', np.nan)
group = group.fillna(group.mode().iloc[0])
group.drop_duplicates(keep='first', inplace=True)
final_df = pd.concat([rows_to_insert, final_df])
但是迭代使我的处理速度非常慢。有人可以建议我更好的方法吗?
样本输入:
a b c d e
a1 b1 c1 NULL e2
a2 b2 c2 NULL NULL
a2 b2 c2 NULL NULL
a1 b1 c3 d4 e4
a1 b1 c1 NULL e2
a1 b1 c1 d1 e2
a1 b1 c1 d1 NULL
样本输出:
a b c d e
a1 b1 c1 d1 e2
a2 b2 c2 NULL NULL
a1 b1 c3 d4 e4
解决方案
groupby().mode
当数据全部时,您需要捕获NaN
:
def get_mode(series):
out = series.mode()
return out.iloc[0] if len(out) else np.nan
df.groupby(['a','b','c'], as_index=False, sort=False).agg(get_mode)
输出:
a b c d e
0 a1 b1 c1 d1 e2
1 a2 b2 c2 NaN NaN
2 a1 b1 c3 d4 e4
如果你想用模式填充你的原始数据框:
df[['d','e']] = df.groupby(['a','b','c']).transform(get_mode)
输出:
a b c d e
0 a1 b1 c1 d1 e2
1 a2 b2 c2 NaN NaN
2 a2 b2 c2 NaN NaN
3 a1 b1 c3 d4 e4
4 a1 b1 c1 d1 e2
5 a1 b1 c1 d1 e2
6 a1 b1 c1 d1 e2