这将是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)