[英]Pandas: sum up multiple columns into one column without last column
如果我有一個類似於這個的數據框
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
這樣的公式可以在一行代碼中解決問題。 然而這並沒有奏效。 有沒有辦法在不明確總結所有列的情況下做到這一點?
這可能對初學者有幫助,所以為了完整起見,如果您知道列名(例如它們在列表中),您可以使用:
column_names = ['Apples', 'Bananas', 'Grapes', 'Kiwis']
df['Fruit Total']= df[column_names].sum(axis=1)
這為您提供了使用哪些列的靈活性,因為您只需操作列表column_names
並且您可以執行諸如僅選擇名稱中帶有字母“a”的列之類的操作。 這樣做的另一個好處是,人們更容易通過列名了解他們在做什么。 將此與list(df.columns)
結合使用,以列表格式獲取列名。 因此,如果您想刪除最后一列,您所要做的就是:
column_names = list(df.columns)
df['Fruit Total']= df[column_names[:-1]].sum(axis=1)
可以在不知道列數甚至沒有 iloc 的情況下執行此操作:
print(df)
Apples Bananas Grapes Kiwis
0 2.0 3.0 NaN 1.0
1 1.0 3.0 7.0 NaN
2 NaN NaN 2.0 3.0
cols_to_sum = df.columns[ : df.shape[1]-1]
df['Fruit Total'] = df[cols_to_sum].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 5.0
在原始 df 上使用df['Fruit Total']= df.iloc[:, -4:-1].sum(axis=1)
不會添加最后一列('Kiwis'),您應該使用df.iloc[:, -4:]
而是選擇所有列:
print(df)
Apples Bananas Grapes Kiwis
0 2.0 3.0 NaN 1.0
1 1.0 3.0 7.0 NaN
2 NaN NaN 2.0 3.0
df['Fruit Total']=df.iloc[:,-4:].sum(axis=1)
print(df)
Apples Bananas Grapes Kiwis Fruit Total
0 2.0 3.0 NaN 1.0 6.0
1 1.0 3.0 7.0 NaN 11.0
2 NaN NaN 2.0 3.0 5.0
如果您想在不知道數據框的形狀/大小的情況下得出總數,我想以 Ramon 的回答為基礎。 我將在下面使用他的答案,但修復一個不包括總數最后一列的項目。 我已經從形狀中刪除了 -1:
cols_to_sum = df.columns[ : df.shape[1]-1]
對此:
cols_to_sum = df.columns[ : df.shape[1]]
print(df)
Apples Bananas Grapes Kiwis
0 2.0 3.0 NaN 1.0
1 1.0 3.0 7.0 NaN
2 NaN NaN 2.0 3.0
cols_to_sum = df.columns[ : df.shape[1]]
df['Fruit Total'] = df[cols_to_sum].sum(axis=1)
print(df)
Apples Bananas Grapes Kiwis Fruit Total
0 2.0 3.0 NaN 1.0 6.0
1 1.0 3.0 7.0 NaN 11.0
2 NaN NaN 2.0 3.0 5.0
然后在不跳過最后一列的情況下為您提供正確的總數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.