[英]How to group by two columns in pandas where the combination of the two is unique
我有一个 dataframe 两列是唯一的,我想分组并能够显示结果。 例如:
import pandas as pd
d = {'label': ['A','A','B','B','B','C','E','E'],
'value': [30,30,40,40,40,0,10,10]}
df = pd.DataFrame(d)
print(df)
结果是
label value
0 A 30
1 A 30
2 B 40
3 B 40
4 B 40
5 C 0
6 E 10
7 E 10
注意所有 A 是 30,B 是 40,等等。
如果我尝试对两者进行groupby
:
grouped = df.groupby(['label','value'])
print(grouped)
结果<pandas.core.groupby.generic.DataFrameGroupBy object at 0x00000208BD8470D0
。
我真的很想摆脱 dataframe 中的这些重复行。
我的目标是得到结果 dataframe:
label value
1 A 30
2 B 40
3 C 0
4 E 10
head可用于获取每个组的前n
行:
import pandas as pd
d = {'label': ['A', 'A', 'B', 'B', 'B', 'C', 'E', 'E'],
'value': [30, 30, 40, 40, 40, 0, 10, 10]}
df = pd.DataFrame(d)
print(df.groupby(['label', 'value']).head(1))
drop_duplicates可用于从 DataFrame 整体中删除重复行:
print(df.drop_duplicates())
Output 对于两者:
label value
0 A 30
2 B 40
5 C 0
6 E 10
假设 df 中还有其他列和重复'label', 'value'
对是唯一应该考虑使用子集标志的值:
import pandas as pd
d = {'label': ['A', 'A', 'B', 'B', 'B', 'C', 'E', 'E'],
'value': [30, 30, 40, 40, 40, 0, 10, 10],
'third': [1, 2, 3, 4, 5, 6, 7, 8]}
df = pd.DataFrame(d)
print(df.drop_duplicates(subset=['label', 'value']))
Output:
label value third
0 A 30 1
2 B 40 3
5 C 0 6
6 E 10 7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.