我的目標是獲取資料框中的前一個元素。我下面的代碼顯示 30,這是當前的代碼。怎么能顯示20,當前的前一個?
import pandas as pd
df1 = pd.DataFrame({'A':[10,20,30]}, index=['2021-11-24','2021-11-25','2021-11-26'])
df1['A']['2021-11-26'] # the current one
uj5u.com熱心網友回復:
使用Series.shift:
df1['A'].shift()['2021-11-26']
# 20
或DataFrame.shift:
df1.shift()['A']['2021-11-26']
# 20
uj5u.com熱心網友回復:
你可以
- 從開始過濾 df 到您擁有的索引值
- 最后拿
import pandas as pd
df = pd.DataFrame({'A': [10, 20, 30]},
index=['2021-11-24', '2021-11-25', '2021-11-26'])
before_idx = df.loc[df.index < '2021-11-26', 'A'].iloc[-1]
print(before_idx)
uj5u.com熱心網友回復:
使用shift和loc:
# fill_value=0 to avoid to get a float number
>>> df1.shift(fill_value=0).loc['2021-11-26', 'A']
20
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369038.html
