我有一个数据框我想在groupby函数中执行mode
操作。我使用以下代码片段做到了
df=df.groupby(['col1','col2']).agg([lambda x:x.mode()[0]]).reset_index()
之后,df在我的数据框中包含lambda作为第一行。
输入:
col1 col2 col3 col4
0 a1 b1 c1 d1
1 a1 b1 c1 d1
2 a1 b1 c2 d2
3 a1 b2 c2 d2
4 a1 b2 c2 d2
5 a1 b2 c3 d3
产量
col1 col2 col3 col4
<lambda> <lambda>
0 a1 b1 c1 d1
1 a1 b2 c2 d2
我有两个问题:
我为什么得到这个纪录?
2.如何删除这个?我的意思是有没有pythonic方式?
从[]
删除agg
以避免MultiIndex
:
df=df.groupby(['col1','col2']).agg(lambda x:x.mode()[0]).reset_index()
print (df)
col1 col2 col3 col4
0 a1 b1 c1 d1
1 a1 b2 c2 d2
一种方法是添加参数as_index=False
:
import pandas as pd
df = pd.DataFrame([['a1', 'b1', 'c'], ['a1', 'b1', 'd'], ['a1', 'b1', 'c']])
res = df.groupby([0, 1], as_index=False)[2].agg(lambda x: x.mode()[0])
# 0 1 2
# 0 a1 b1 c