python中pandas.DataFrame对行与列求和及添加新行与列示例
本文介绍的是python中pandas.DataFrame对行与列求和及添加新行与列的相关资料,下面话不多说,来看看详细的介绍吧。
方法如下:
导入模块:
from pandas import DataFrame import pandas as pd import numpy as np
生成DataFrame数据
df = DataFrame(np.random.randn(4, 5), columns=['A', 'B', 'C', 'D', 'E'])
DataFrame数据预览:
A B C D E 0 0.673092 0.230338 -0.171681 0.312303 -0.184813 1 -0.504482 -0.344286 -0.050845 -0.811277 -0.298181 2 0.542788 0.207708 0.651379 -0.656214 0.507595 3 -0.249410 0.131549 -2.198480 -0.437407 1.628228
计算各列数据总和并作为新列添加到末尾
df['Col_sum'] = df.apply(lambda x: x.sum(), axis=1)
计算各行数据总和并作为新行添加到末尾
df.loc['Row_sum'] = df.apply(lambda x: x.sum())
最终数据结果:
A B C D E Col_sum 0 0.673092 0.230338 -0.171681 0.312303 -0.184813 0.859238 1 -0.504482 -0.344286 -0.050845 -0.811277 -0.298181 -2.009071 2 0.542788 0.207708 0.651379 -0.656214 0.507595 1.253256 3 -0.249410 0.131549 -2.198480 -0.437407 1.628228 -1.125520 Row_sum 0.461987 0.225310 -1.769627 -1.592595 1.652828 -1.022097
相关推荐
81510295 2020-11-17
roamer 2020-10-29
listep 2020-09-11
Tristahong 2020-08-24
三石 2020-08-23
QianYanDai 2020-08-16
Johnson0 2020-07-28
mmmjyjy 2020-07-16
santiago00 2020-07-11
QianYanDai 2020-07-05
QianYanDai 2020-07-05
jiahaohappy 2020-06-21
QianYanDai 2020-06-16
Oeljeklaus 2020-05-29
zhangxiaojiakele 2020-05-25
人家 2020-05-17
jzlixiao 2020-05-15
柠檬班 2020-05-16
jiahaohappy 2020-05-12