我有兩個 DataFrame - df1 和 df2。它們都包含一個日期時間列,比如 date1 和 date2。我想將 date1 列的每個值與 date2 匹配并將索引存盤在新列中。我正在嘗試以下代碼:
df1['location'] = df2.loc[df1['date1'] == df2['date2']]
但是這一行拋出了以下錯誤:
只能比較具有相同標簽的系列物件。
我還嘗試使用 index 函式,如下所示:
df1['location'] = df2.index(df1['date1'] == df2['date2'])
這也引發了與之前的代碼相同的錯誤。
如何從 df2 DataFrame 中獲取與 df1 DataFrame 中的日期匹配的日期索引?我需要對 df1 中的每個值執行此操作。
uj5u.com熱心網友回復:
for i, row in df2.iterrows():
df1.loc[df1['date1'] == df2.at[i, 'date2'], 'location'] = i
uj5u.com熱心網友回復:
嘗試設定一個MRE:
df1 = pd.DataFrame({'date1': pd.date_range('2022-1-1', periods=5, freq='D')})
df2 = pd.DataFrame({'date2': pd.date_range('2022-1-3', periods=4, freq='D')})
# df1
# date1
# 0 2022-01-01
# 1 2022-01-02
# 2 2022-01-03
# 3 2022-01-04
# 4 2022-01-05
# df2
# date2
# 0 2022-01-03
# 1 2022-01-04
# 2 2022-01-05
# 3 2022-01-06
df2用date2列交換當前索引并將系列映射到date1列df1:
df1['location'] = df1['date1'].map(df2.reset_index().set_index('date2')['index'])
print(df1)
# Output
date1 location
0 2022-01-01 NaN
1 2022-01-02 NaN
2 2022-01-03 0.0
3 2022-01-04 1.0
4 2022-01-05 2.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/409567.html
標籤:
上一篇:如何將日期轉換為季度
