gpt4 book ai didi

python - DataFrame.groupby() 和 max() 出现意外结果

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:43 25 4
gpt4 key购买 nike

假设我有一个包含姓名、性别及其计数的 CSV。

我正在使用 groupby() 和 max() 查找多数名称。但我从结果中发现了一些奇怪的事情:

CSV:

Name     Gender  Count
Connie F 90
Connie F 78
Peter M 200
Connie M 5
Connie F 94
Connie F 67
John M 100
Connie F 73
Connie F 82
Connie F 73
May F 65

代码的第一部分看起来不错:

>>>data = pd.read_csv('names.txt',names=['Name','Gender','Count'])
>>>data = data.groupby(['Name','Gender']).sum().reset_index()
>>>print (data)
Name Gender Count
0 Connie F 557
1 Connie M 5
2 John M 100
3 May F 65
4 Peter M 200

有两条包含“Connie”的记录,我需要选择最多的一条。

>>>data= data.groupby(['Name']).max().reset_index()
>>>print(data)
Name Gender Count
0 Connie M 557
1 John M 100
2 May F 65
3 Peter M 200

我是否做错了什么,导致“Connie”的性别是 M 而不是 F?而最大计数是正确的

最佳答案

这是正确的,因为M > F,更好的解释是here .

我还发现this ,因此 automatic exclusion of nuisance columns 不会省略 string 列:

strings have lt() defined so the built in min() and max() work on them. If the non-numeric object supports the proper comparison methods, min() and max() aggregate functions should be non-ambiguous.

print (data.groupby(['Name'])['Gender'].max())
Name
Connie M
John M
May F
Peter M
Name: Gender, dtype: object

为了正确输出需要idxmax获取 Count 列中每组最大值的索引,然后按 loc 选择:

print (data.groupby(['Name'])['Count'].idxmax())
Name
Connie 0
John 2
May 3
Peter 4
Name: Count, dtype: int64

data = data.loc[data.groupby(['Name'])['Count'].idxmax()]
print (data)
Name Gender Count
0 Connie F 557
2 John M 100
3 May F 65
4 Peter M 200

关于python - DataFrame.groupby() 和 max() 出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47588594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com