我已经尝试找到如何附加一个Total Row
,它可以对列进行求和。
这个问题有一个很好的解决方案:
但是,在使用此方法时,我注意到一条警告消息:
FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
为了避免使用遗留代码,我尝试使用此替代方案。当我尝试使用concat
方法时,它垂直地将sum行追加到最后一列。
代码我使用了
pd.concat( [df, df.sum(numeric_only=True)] )
结果
a b c d e
0 2200.0 14.30 NaN 2185.70 NaN
1 3200.0 20.80 NaN 3179.20 NaN
2 6400.0 41.60 NaN 6358.40 NaN
3 NaN NaN NaN NaN 11800.00 <-- Appended using Concat
4 NaN NaN NaN NaN 76.70 <-- Appended using Concat
5 NaN NaN NaN NaN 0.00 <-- Appended using Concat
6 NaN NaN NaN NaN 11723.30 <-- Appended using Concat
我想要什么
a b c d
0 2200.0 14.30 NaN 2185.70
1 3200.0 20.80 NaN 3179.20
2 6400.0 41.60 NaN 6358.40
3 11800.00 76.70 0.00 11723.30 <-- Appended using Concat
使用concat
方法解决这个问题是否有一个很好的解决方案?
发布于 2022-03-02 10:08:08
将和(即pandas.Series
)转换为DataFrame,并在concat
之前转置
>>> pd.concat([df,df.sum().to_frame().T], ignore_index=True)
a b c d
0 2200.0 14.3 NaN 2185.7
1 3200.0 20.8 NaN 3179.2
2 6400.0 41.6 NaN 6358.4
3 11800.0 76.7 0.0 11723.3
https://stackoverflow.com/questions/71327125
复制相似问题