熊猫:求和给定列的DataFrame行

问题:熊猫:求和给定列的DataFrame行

我有以下DataFrame:

In [1]:

import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df
Out [1]:
   a  b   c  d
0  1  2  dd  5
1  2  3  ee  9
2  3  4  ff  1

我想增加一列'e'是列的总和'a''b''d'

在各个论坛上,我认为这样会起作用:

df['e'] = df[['a','b','d']].map(sum)

但事实并非如此。

我想知道适当的操作与列的列表['a','b','d']df作为输入。

I have the following DataFrame:

In [1]:

import pandas as pd
df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df
Out [1]:
   a  b   c  d
0  1  2  dd  5
1  2  3  ee  9
2  3  4  ff  1

I would like to add a column 'e' which is the sum of column 'a', 'b' and 'd'.

Going across forums, I thought something like this would work:

df['e'] = df[['a','b','d']].map(sum)

But it didn’t.

I would like to know the appropriate operation with the list of columns ['a','b','d'] and df as inputs.


回答 0

您可以sum设置参数axis=1以对行求和,这将忽略任何数字列:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

如果您只想汇总特定的列,则可以创建列的列表并删除不感兴趣的列:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

回答 1

如果您只需要汇总几列,则可以编写:

df['e'] = df['a'] + df['b'] + df['d']

这将创建e具有以下值的新列:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

对于较长的列列表,首选EdChum的答案。

If you have just a few columns to sum, you can write:

df['e'] = df['a'] + df['b'] + df['d']

This creates new column e with the values:

   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

For longer lists of columns, EdChum’s answer is preferred.


回答 2

创建要添加的列名列表。

df['total']=df.loc[:,list_name].sum(axis=1)

如果要某些行的总和,请使用“:”指定行

Create a list of column names you want to add up.

df['total']=df.loc[:,list_name].sum(axis=1)

If you want the sum for certain rows, specify the rows using ‘:’


回答 3

这是使用iloc选择要累加的列的更简单方法:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

生成:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

我找不到一种将范围和特定列结合起来的方法,例如:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

This is a simpler way using iloc to select which columns to sum:

df['f']=df.iloc[:,0:2].sum(axis=1)
df['g']=df.iloc[:,[0,1]].sum(axis=1)
df['h']=df.iloc[:,[0,3]].sum(axis=1)

Produces:

   a  b   c  d   e  f  g   h
0  1  2  dd  5   8  3  3   6
1  2  3  ee  9  14  5  5  11
2  3  4  ff  1   8  7  7   4

I can’t find a way to combine a range and specific columns that works e.g. something like:

df['i']=df.iloc[:,[[0:2],3]].sum(axis=1)
df['i']=df.iloc[:,[0:2,3]].sum(axis=1)

回答 4

当我按顺序排列列时,以下语法对我有帮助

awards_frame.values[:,1:4].sum(axis =1)

Following syntax helped me when I have columns in sequence

awards_frame.values[:,1:4].sum(axis =1)

回答 5

您只需将数据框传递给以下函数即可

def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
    frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
    return(frame)

范例

我有一个数据框(awards_frame)如下:

…并且我想创建一个新列,显示每一行的奖励总和

用法

我只是通过我的awards_frame进入功能,同时指定名称的新列的,和列表将被归纳列名:

sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])

结果

You can simply pass your dataframe into the following function:

def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
    frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
    return(frame)

Example:

I have a dataframe (awards_frame) as follows:

…and I want to create a new column that shows the sum of awards for each row:

Usage:

I simply pass my awards_frame into the function, also specifying the name of the new column, and a list of column names that are to be summed:

sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])

Result:


回答 6

这里最简单的方法是使用

    df.eval('e = a + b + d')

The shortest and simpliest way here is to use

    df.eval('e = a + b + d')