[英]Pandas Dataframe groupby one column and sum of all other columns
我有一个看起来像这样的 pandas dataframe
genre1 genre2 genre3 Votes1 votes2 votes3 ......… cnt
Comedy Animation Drama 8.3 7.0 8.5 1
Adventure Comedy Mystery 6.4 8.2 3.5 1
Drama Music Sci-Fi 3.8 6.2 5.9 1
.
.
.
我想为每个 dataframe 分别使用各个类型的分组和所有其他数字列的总和创建 3 个新数据帧。 我尝试了 groupby 的不同变体,pandas 的总和,但我无法弄清楚如何将 groupby sum 一起应用以给出如图所示的结果。 请分享您可能有的任何想法。 谢谢!
当您执行df.groupby().sum()
时,您将得到一个 DataFrame ,其中每列总和一列,索引将是不同的组。
此外,您可以将列名列表传递给groupby()
。 所以你可以这样做: df.groupby(["genre1", "genre2", "genre3"])
例子:
>>> df = pd.DataFrame(
{
"hello": ["world", "brave", "world", "brave",],
"num1": [1, 2, 3, 4],
"num2": [1, 2, 3, 4]
}
)
>>> df
hello num1 num2
0 world 1 1
1 brave 2 2
2 world 3 3
3 brave 4 4
>>> df.groupby("hello").sum()
num1 num2
hello
brave 6 6
world 4 4
>>> df.groupby("hello").sum().columns
Index(['num1', 'num2'], dtype='object')
>>> df.groupby("hello").sum().index
Index(['brave', 'world'], dtype='object', name='hello')
>>> df = pd.DataFrame(
{
"hello1": ["world", "brave", "world", "brave",],
"hello2": ["new", "world", "brave", "new",],
"num1": [1, 2, 3, 4],
"num2": [1, 2, 3, 4]
}
)
>>> df.groupby(["hello1", "hello2"]).sum()
num1 num2
hello1 hello2
brave new 4 4
world 2 2
world brave 3 3
new 1 1
这应该会给你你正在寻找的结果,但是如果你想要多个 DataFrames,你可能必须将 output DataFrame 中的数据复制到你想要在其自己的 ZBA834BA059A9A379E88E4Z 中的每一列的新 DataFrames 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.