【发布时间】:2021-02-04 21:27:36
【问题描述】:
我已经看到了许多其他相关的 SO 问题,例如 this 和 this,但它们似乎并不是我想要的。假设我有一个这样的数据框:
import pandas as pd
df = pd.DataFrame(columns=['patient', 'parent csn', 'child csn', 'days'])
df.loc[0] = [0, 0, 10, 5]
df.loc[1] = [0, 0, 11, 3]
df.loc[2] = [0, 1, 12, 6]
df.loc[3] = [0, 1, 13, 4]
df.loc[4] = [1, 2, 20, 4]
df
Out[9]:
patient parent csn child csn days
0 0 0 10 5
1 0 0 11 3
2 0 1 12 6
3 0 1 13 4
4 1 2 20 4
现在我想做的是这样的:
grp_df = df.groupby(['parent csn']).min()
问题是结果计算了 所有 列(不是parent csn)的最小值,并产生:
grp_df
patient child csn days
parent csn
0 0 10 3
1 0 12 4
2 1 20 4
您可以看到,对于第一行,days 数字和 child csn 数字不再像分组之前那样位于同一行。这是我想要的输出:
grp_df
patient child csn days
parent csn
0 0 11 3
1 0 13 4
2 1 20 4
我怎样才能得到它?我有遍历数据框的代码,我认为它会起作用,但是即使使用 Cython,它也很慢。我觉得这应该是显而易见的,但我不这么认为。
我也查看了this 的问题,但是将child csn 放在groupby 列表中是行不通的,因为child csn 与days 不同。
This 的问题似乎更有可能,但我没有找到非常直观的解决方案。
This 的问题似乎也很可能,但同样,答案不是很直观,而且我确实希望每个 parent csn 只占一行。
另一个细节:包含最小days 值的行可能不是唯一的。在这种情况下,我只想要一排 - 我不在乎。
非常感谢您的宝贵时间!
【问题讨论】:
标签: python-3.x pandas pandas-groupby aggregate