팬더 : 주어진 열에 대한 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
입력으로 작업을 실현하고 싶습니다 .
당신은 할 수 sum
와 세트 PARAM 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
요약 할 열이 몇 개인 경우 다음과 같이 쓸 수 있습니다.
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의 답변이 선호됩니다.
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)
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 ':'
Following syntax helped me when I have columns in sequence
awards_frame.values[:,1:4].sum(axis =1)
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:
참고URL : https://stackoverflow.com/questions/25748683/pandas-sum-dataframe-rows-for-given-columns
'Programming' 카테고리의 다른 글
IPython / Jupyter Notebook에서 줄 번호 표시 (0) | 2020.07.12 |
---|---|
HDFS에서 로컬 파일 시스템으로 파일을 복사하는 방법 (0) | 2020.07.12 |
Bash / sh-&&와;의 차이점 (0) | 2020.07.12 |
Visual Studio Team Services에서 Git Bash를 사용하여 인증 할 수 없음 (0) | 2020.07.12 |
MySQL 쿼리를 CSV로 변환하는 PHP 코드 (0) | 2020.07.12 |