我已经看到许多其他相关的 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
值的行可能不是唯一的。在那种情况下,我只想要一行 - 我不在乎是哪一行。
非常感谢您的宝贵时间!
最佳答案
您可以使用 .idxmin()
而不是 .min()
来获取索引(行标识符),其中“天数”最少每组:
数据创建:
import pandas as pd
data = [[0, 0, 10, 5],
[0, 0, 11, 3],
[0, 1, 12, 6],
[0, 1, 13, 4],
[1, 2, 20, 4]]
df = pd.DataFrame(data, columns=['patient', 'parent csn', 'child csn', 'days'])
print(df)
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
day_minimum_row_indices = df.groupby("parent csn")["days"].idxmin()
print(day_minimum_row_indices)
parent csn
0 1
1 3
2 4
Name: days, dtype: int64
由此您可以看到组父 csn 0 在第 1 行的天数最少。回顾我们的原始数据框,我们可以看到第 1 行的天数 == 3,实际上是最小天数的位置父 csn == 0 的天数。父 csn == 1 在第 3 行有最少天数,依此类推。
我们可以使用行索引将子集返回到我们的原始数据框中:
new_df = df.loc[day_minimum_row_indices]
print(new_df)
patient parent csn child csn days
1 0 0 11 3
3 0 1 13 4
4 1 2 20 4
编辑(tldr):
df.loc[df.groupby("parent csn")["days"].idxmin()]
关于python-3.x - Python Pandas : groupby one column, 只在另外一列聚合,取对应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64472480/