我有一个df,如下所示.我已经添加了一个包含所有行的合计的新列和一个包含所有列的合计的新行:

A  B  C   D   Total
-------------------
1  2   3   4   10
5  6   7   8   26
6  8  10  12   36

现在我需要再添加一行,该行的第一个元素将是NaN,其余的将是从Total行的前一列中减go 的列.

A B C D Total
1 2 3 4 10
5 6 7 8 26
6 8 10 12 36
NaN 2 2 2 24 <--- new row

谢谢

推荐答案

这将是df.append很少使用的用例之一,但是您可以提取最后一行的iloc[-1]diff的各个值,然后将其与原始值组合在一起.

Option 1
One method of doing this concatenation would be using pd.concat

df2 = pd.concat([df, df.iloc[-1].diff().to_frame().T])
print (df2) 

     A    B     C     D  Total
0  1.0  2.0   3.0   4.0   10.0
1  5.0  6.0   7.0   8.0   26.0
2  6.0  8.0  10.0  12.0   36.0
2  NaN  2.0   2.0   2.0   24.0

哪里,

df.iloc[-1].diff().to_frame().T # dataframe with 1 row

    A    B    C    D  Total
2 NaN  2.0  2.0  2.0   24.0

Option 2
An alternative using inplace assignment with loc:

df.loc[len(df.index)] = df.iloc[-1].diff()
print (df)

     A    B     C     D  Total
0  1.0  2.0   3.0   4.0   10.0
1  5.0  6.0   7.0   8.0   26.0
2  6.0  8.0  10.0  12.0   36.0
3  NaN  2.0   2.0   2.0   24.0

哪里,

df.iloc[-1].diff()  # series

A         NaN
B         2.0
C         2.0
D         2.0
Total    24.0
Name: 2, dtype: float64

Option 3
Here's an option that has a bit of fun with dictionaries and pd.DataFrame:

pd.DataFrame([*df.to_dict('records'), df.iloc[-1].diff().to_dict()])

     A    B     C     D  Total
0 1.00 2.00  3.00  4.00  10.00
1 5.00 6.00  7.00  8.00  26.00
2 6.00 8.00 10.00 12.00  36.00
3  NaN 2.00  2.00  2.00  24.00

Option 4 [deprecated]
On older versions (pandas <= 1.4) I would have recommended using append like this:

df2 = df.append(df.iloc[-1].diff(), ignore_index=True)

Python相关问答推荐

为什么Pydantic在我申报邮箱时说邮箱丢失

在有限数量的唯一字母的长字符串中,找到包含重复不超过k次的所有唯一字母的最长子字符串

回归回溯-2D数组中的单词搜索

当pip为学校作业(job)安装sourcefender时,我没有收到匹配的分发错误.我已经try 过Python 3.8.10和3.10.11

除了Python之外,可以替代bare?

使用argsorted索引子集索引数组

Matplotlib轮廓线值似乎不对劲

为什么dict(id=1,**{id:2})有时会引发KeyMessage:id而不是TypMessage?

从DataFrame.apply创建DataFrame

在Python中为变量的缺失值创建虚拟值

如何使用SubProcess/Shell从Python脚本中调用具有几个带有html标签的参数的Perl脚本?

Chatgpt API不断返回错误:404未能从API获取响应

多处理代码在while循环中不工作

Pandas 第二小值有条件

比较2 PD.数组的令人惊讶的结果

numba jitClass,记录类型为字符串

非常奇怪:tzLocal.get_Localzone()基于python3别名的不同输出?

无法定位元素错误404

Pandas—合并数据帧,在公共列上保留非空值,在另一列上保留平均值

如何在海上配对图中使某些标记周围的黑色边框