如何从 python 中的 df 中减去(最后一列,最后一行)减去(最后一列,第一行)

How to substract (last column, last row) minus (last column, first row) from a df in python

我有一个数据框,索引是日期时间,列是整数。我正在尝试执行以下操作(最后一列最后一行减去最后一列第一行)。我很难获得正确的输出。请帮忙。

df8['new_port'] = df8.mean(axis=1)
print(df8)

print(df8['new_port'].iloc[-1:])
print(df8['new_port'].iloc[:1])
print(df8['new_port'].iloc[:1] - df8['new_port'].iloc[-1:])

输出如下

问题是您在 df8['new_port'].iloc[-1:] 时选择了一组元素。

您必须删除冒号才能选择最后一个元素。

df8['new_port'].iloc[-1] # last row element from your last column 
df8['new_port'].iloc[0] # first row element from your last column 
df8.iloc[-1,-1] # last row last column
df8.iloc[0,-1] # first row last column
df8.iat[-1,-1]  # last row last column
df8.iat[0,-1] # first row last column

或者像 Sayandip Dutta 所说的那样容易得多

df8['new_port'].iat[1] - df8['new_port'].iat[-1]