pandas 熊猫:将数据框中的多列汇总到一个新列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50902416/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:42:45  来源:igfitidea点击:

Panda: Summing multiple columns in dataframe to a new column

pythonpandasdataframesum

提问by Tashaho

I want to sum multiple columns of dataframe to a new column. For 2 columns I was using this.

我想将多列数据框相加到一个新列。对于 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)

But, for my project, I need to do sums of around 15-20 columns. Every time I do not want to write df['col1']+df['col2']+......................

但是,对于我的项目,我需要做大约 15-20 列的总和。每次都不想写df['col1']+df['col2']+........

I have the list of columns, which I have to add. Like:

我有必须添加的列列表。喜欢:

'col1'+'col2'+ 'col5'+'col8'+----+'col18'

'col1'+'col2'+'col5'+'col8'+----+'col18'

or like this:

或者像这样:

'col1', 'col2', 'col5', 'col8',----,'col18'

'col1', 'col2', 'col5', 'col8',----,'col18'

How can I use this list directly to do the sum of columns?

如何直接使用此列表来计算列的总和?

回答by Vipul Sharma

Try slicing the columns:

尝试切片列:

import pandas as pd
df = pd.read_csv("whatever.csv")
df.loc[:,'col1':'col18'].sum(axis = 1)