我有一个pandas的数据框架,看起来像这样的
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
.
.
.
我想创建3个新的数据框架,使用各个流派的groupby和所有其他数字列的总和分别为每个数据框架.我已经尝试了groupby的不同变化,pandas的总和,但我无法弄清楚如何应用groupby总和一起给出的结果,如所示。请分享你可能有的任何想法。谢谢!我有一个pandas数据表格。
当你做 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
这应该可以得到你想要的结果,但是如果你想要多个DataFrame,你可能需要把输出DataFrame中的数据复制到新的DataFrame中,让每一列都有自己的DataFrame。