[英]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.