如何从 GroupBy.apply() 中删除多索引?
How to remove the multiindex from GroupBy.apply()?
基于 .
df = pandas.DataFrame([[2001, "Jack", 77], [2005, "Jack", 44], [2001, "Jill", 93]],columns=['Year','Name','Value'])
Year Name Value
0 2001 Jack 77
1 2005 Jack 44
2 2001 Jill 93
For each unique Name, I would like to keep the row with the largest
Year value. In the above example I would like to get the table
Year Name Value
0 2005 Jack 44
1 2001 Jill 93
我尝试用 groupby
+ (apply
):
来解决这个问题
df.groupby('Name', as_index=False)\
.apply(lambda x: x.sort_values('Value').head(1))
Year Name Value
0 0 2001 Jack 44
1 2 2001 Jill 93
不是最好的方法,但我对正在发生的事情及其原因更感兴趣。结果有一个 MultiIndex
,看起来像这样:
MultiIndex(levels=[[0, 1], [0, 2]],
labels=[[0, 1], [0, 1]])
我不是在寻找解决方法。我实际上更想知道为什么会发生这种情况,以及如何在不改变我的方法的情况下防止它。
IIUC,使用group_keys=False
:
df.groupby('Name', group_keys=False).apply(lambda x: x.sort_values('Value').head(1))
输出:
Year Name Value
1 2005 Jack 44
2 2001 Jill 93
基于
df = pandas.DataFrame([[2001, "Jack", 77], [2005, "Jack", 44], [2001, "Jill", 93]],columns=['Year','Name','Value']) Year Name Value 0 2001 Jack 77 1 2005 Jack 44 2 2001 Jill 93
For each unique Name, I would like to keep the row with the largest Year value. In the above example I would like to get the table
Year Name Value 0 2005 Jack 44 1 2001 Jill 93
我尝试用 groupby
+ (apply
):
df.groupby('Name', as_index=False)\
.apply(lambda x: x.sort_values('Value').head(1))
Year Name Value
0 0 2001 Jack 44
1 2 2001 Jill 93
不是最好的方法,但我对正在发生的事情及其原因更感兴趣。结果有一个 MultiIndex
,看起来像这样:
MultiIndex(levels=[[0, 1], [0, 2]],
labels=[[0, 1], [0, 1]])
我不是在寻找解决方法。我实际上更想知道为什么会发生这种情况,以及如何在不改变我的方法的情况下防止它。
IIUC,使用group_keys=False
:
df.groupby('Name', group_keys=False).apply(lambda x: x.sort_values('Value').head(1))
输出:
Year Name Value
1 2005 Jack 44
2 2001 Jill 93