我有一個資料框(下)。我想比較索引列中的兩個值。第一個索引值是最后一個索引的值。第二個索引值是基于條件標準的索引值(索引對應于1)。
換句話說,我如何讓 d2 具有與 d1 相同的格式(我希望 d2 能夠將 index 的值對應為 1)?(之后我想計算 d1 和 d2 之間的數值差異)(類似于 df1.index[-1]-df1.index[ ]).days = 3)
提前致謝
import pandas as pd
df1 = pd.DataFrame({"date": ['2021-3-22', '2021-3-23', '2021-3-24', '2021-3-25', '2021-3-26'],
"x": ['nan', 1, 'nan', 'nan', 'nan' ]})
df1['date'] = pd.to_datetime(df1['date'])
df1.set_index('date', inplace=True)
df1
date x
2021-03-22 nan
2021-03-23 1
2021-03-24 nan
2021-03-25 nan
2021-03-26 nan
d1 = df1.index[-1]
d1
Timestamp('2021-03-26 00:00:00')
d2=df1.x[df1.x == 1]
d2
date
2021-03-23 1
Name: x, dtype: object
(I would like to have d1-d2 =3)
PS如果,這是Dataframe的后續問題:索引值差異計算
uj5u.com熱心網友回復:
# subtract the index (which are datetime) and take the difference as days
(df1.index[-1] - df1[df1.x == 1].index).days[0]
>>> 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/526503.html
標籤:Python熊猫数据框
