我想知道我需要做些什么来过滤数据框,保留Name
列的唯一值,从Value
列中添加值以及添加新列以计数每个外观Name
我有什么?
Name Type Value
0 apple A 1
1 banana B 3
2 apple A 2
3 pear P 4
4 apple A 6
5 carrot C 3
6 banana B 2
,我想将其过滤到此:
Name Type AddedValue Occurrences
0 apple A 9 3
1 banana B 5 2
2 pear P 4 1
3 carrot C 3 1
我该怎么办?我已经尝试过设想一个带有.join
条件集的where
方法,但是我无法使其工作,并且我确定问题是我正在尝试翻译pythonic的想法一条熊猫指令,可以通过精美的矢量运算或类似的方法解决我的问题
预先感谢
答案 0 :(得分:4)
尝试groupby
方法:
df.groupby(["Name","Type"]).agg(["count","sum"])
结果:
Value
count sum
Name Type
apple A 3 9
banana B 2 5
carrot C 1 3
pear P 1 4
但是,如果您想展平列/索引使用:
df2 = df.groupby(["Name","Type"]).agg(["count","sum"]).reset_index(drop=False)
df2.columns = [' '.join(col).strip() for col in df2.columns.values]
输出:
Name Type Value count Value sum
0 apple A 3 9
1 banana B 2 5
2 carrot C 1 3
3 pear P 1 4
借助@piRSquared,甚至可以提供更优雅的解决方案:
df2 = df.groupby(['Name', 'Type']).Value.agg([('AddedValue', 'sum'), ('Occurences', 'count')]).reset_index(drop=False)
输出:
Name Type AddedValue Occurences
0 apple A 9 3
1 banana B 5 2
2 carrot C 3 1
3 pear P 4 1
答案 1 :(得分:1)
是的,就像ipj回答的那样,您可以在Pandas Groupby中尝试groupby方法。
df = df.groupby(["Name","Type"]).agg(["count","sum"])
df.columns = df.columns.droplevel(0)
df = df.rename({"count": "AddedValue", "sum": "Occurrences"}, axis=1)