本文介紹了 pandas :將多列匯總為一列,沒有最后一列的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如果我有一個類似于這個的數據框
If I have a dataframe similar to this one
Apples Bananas Grapes Kiwis
2 3 nan 1
1 3 7 nan
nan nan 2 3
我想添加這樣的列
Apples Bananas Grapes Kiwis Fruit Total
2 3 nan 1 6
1 3 7 nan 11
nan nan 2 3 5
我猜你可以使用 df['Apples'] + df['Bananas']
等等,但我的實際數據框比這大得多.我希望像 df['Fruit Total']=df[-4:-1].sum
這樣的公式可以在一行代碼中解決問題.然而這并沒有奏效.有沒有辦法在不明確總結所有列的情況下做到這一點?
I guess you could use df['Apples'] + df['Bananas']
and so on, but my actual dataframe is much larger than this. I was hoping a formula like df['Fruit Total']=df[-4:-1].sum
could do the trick in one line of code. That didn't work however. Is there any way to do it without explicitly summing up all columns?
推薦答案
可以先通過 iloc
然后是 sum
:
You can first select by iloc
and then sum
:
df['Fruit Total']= df.iloc[:, -4:-1].sum(axis=1)
print (df)
Apples Bananas Grapes Kiwis Fruit Total
0 2.0 3.0 NaN 1.0 5.0
1 1.0 3.0 7.0 NaN 11.0
2 NaN NaN 2.0 3.0 2.0
所有列的總和使用:
df['Fruit Total']= df.sum(axis=1)
這篇關于 pandas :將多列匯總為一列,沒有最后一列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!