[英]Matching datetime column in pandas with another datetime column and return index
我有兩個 DataFrame - df1 和 df2。 它們都包含一個日期時間列,比如 date1 和 date2。 我想將 date1 列的每個值與 date2 匹配並將索引存儲在新列中。 我正在嘗試以下代碼:
df1['location'] = df2.loc[df1['date1'] == df2['date2']]
但是這一行拋出了以下錯誤:
只能比較具有相同標簽的系列對象。
我還嘗試使用索引 function 如下:
df1['location'] = df2.index(df1['date1'] == df2['date2'])
這也引發了與之前的代碼相同的錯誤。
如何從 df2 DataFrame 中獲取與 df1 DataFrame 中的日期匹配的日期索引? 我需要對 df1 中的每個值執行此操作。
嘗試設置一個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
列和 map 系列交換到df1
的date1
列:
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
for i, row in df2.iterrows():
df1.loc[df1['date1'] == df2.at[i, 'date2'], 'location'] = i
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.