Pandas>>按照行、列进行求和 - 简书 (jianshu.com)
Pandas操作dataframe对所有列/行求和 ,对指定列/行求和,对某一列/行求和,并添加新的列/行_dataframe横向求和-CSDN博客
0- 对列求和(某几列,不是全部)并保存到最后一行
数据:
data_test= pd.DataFrame([
['张三',1,1],
['李四',2,2],
['张三',3,3],
['张三',4,4],
['王五',5,5],
['王五',6,6,],
['赵六',7,7]
],
columns =['name','number_1','number_2']
)
如下:
df['Row_sum'] = df.iloc[:,0:2].sum(axis=1) # 对0,1列按行求和,生成新列
df.loc['Col_sum1'] = df.iloc[0:2,:].sum(axis=0) # 对0,1行按列求和,生成新行
df.loc['Col_sum2'] = df.iloc[0:2,:].sum(axis=1) # 对0,1行按行求和,生成新行
df
df['Row_sum'] = df.iloc[:,0:2].sum(axis=1) # 对0,1列按行求和,生成新列
df.loc['Col_sum1'] = df.iloc[0:2,:].sum(axis=0) # 对0,1行按列求和,生成新行
df.loc['Col_sum2'] = df.iloc[0:2,:].sum(axis=1) # 对0,1行按行求和,生成新行
df
1- 对列求和 并保存到最后一行
代码
#!/usr/bin/python
# -*- coding: utf8 -*-
import pandas as pd
创建示例DataFrame
=============
df = pd.DataFrame({'A': \[1, 2, 3\], 'B': \[4, 5, 6\], 'C': \[7, 8, 9\]})
print df
按列求和,并将结果转换为DataFrame
=====================
sum_col = pd.DataFrame(df.sum(axis=0), columns=\['Total'\]).T
将列求和结果添加到DataFrame的最后一列
=======================
df = pd.concat(\[df, sum_col\], axis=0)
`print(df)`
2- 对行求和:
#!/usr/bin/python
# -*- coding: utf8 -*-
import pandas as pd
创建示例DataFrame
=============
df = pd.DataFrame({'A': \[1, 2, 3\], 'B': \[4, 5, 6\], 'C': \[7, 8, 9\]})
print df
按行求和,并将结果转换为DataFrame
=====================
sum_row = pd.DataFrame(df.sum(axis=1), columns=\['Total'\])
将行求和结果添加到DataFrame的最后一行
=======================
df = pd.concat(\[df, sum_row\], axis=1)
`print(df)`