我想将多列dataframe汇总到一个新列。对于2列我正在使用它。
import pandas as pd, numpy as np
df=pd.read_csv("Calculation_test.csv")
#creating new colums
df["Test1"] = 0
#sum of 2 columns
df["Test1"]= df['col1']+df['col2']
df.to_csv('test_cal.csv', index=False)
但是,对于我的项目,我需要做大约15-20列的总和。每次我都不想写df [' col1'] + df [' col2'] + .................. ....
我有列的列表,我必须添加。像:
' col1' +' col2' +' col5' +' col8' + ---- +' col18&# 39;
或者像这样:
' col1',' col2',' col5',' col8',----,' col18&# 39;
如何直接使用此列表来完成列的总和?
答案 0 :(得分:1)
尝试切片列:
import pandas as pd
df = pd.read_csv("whatever.csv")
df.loc[:,'col1':'col18'].sum(axis = 1)