我的代碼中出現問題的部分如下。我打開一個 CSV 檔案,想從最后一行中減去第一行,然后將其附加到一個新檔案中。我在嘗試時收到錯誤 KeyError: 96。我知道問題是 df[96]-df

uj5u.com熱心網友回復:
您可以使用iloc選擇第一行和最后一行,然后減去
import pandas as pd
import numpy as np
#Create a test df
np.random.seed(1)
df = pd.DataFrame({
'col1':np.random.choice(10,6),
'col2':np.random.choice(10,6),
'col3':np.random.choice(10,6),
})
#subtract the first row from the last row
first_ind = 0
last_ind = len(df)-1
diff_row = df.iloc[last_ind]-df.iloc[first_ind]
print(diff_row)
這是創建的測驗 df:
col1 col2 col3
0 5 1 5
1 8 7 2
2 9 6 4
3 5 9 2
4 0 2 4
5 0 4 7
然后diff_row等于:
col1 -5
col2 3
col3 2
dtype: int64
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360599.html
上一篇:InvalidParameterValueException:無法訪問流
下一篇:生成CSV,一列內的數字陣列
