简体   繁体   English

将 pandas 中的日期时间列与另一个日期时间列和返回索引匹配

[英]Matching datetime column in pandas with another datetime column and return index

I have two DataFrames - df1 and df2.我有两个 DataFrame - df1 和 df2。 Both of them contain a datetime column, say date1 and date2.它们都包含一个日期时间列,比如 date1 和 date2。 I want to match each value of date1 column to date2 and store the index in a new column.我想将 date1 列的每个值与 date2 匹配并将索引存储在新列中。 I am trying the following code:我正在尝试以下代码:

df1['location'] = df2.loc[df1['date1'] == df2['date2']]

but this line throws out following error:但是这一行抛出了以下错误:

Can only compare identically-labeled series objects.只能比较具有相同标签的系列对象。

I also tried using the index function as follows:我还尝试使用索引 function 如下:

df1['location'] = df2.index(df1['date1'] == df2['date2'])

This also raised the same error as the previous code.这也引发了与之前的代码相同的错误。

How can I get the index of date from df2 DataFrame which matches date in df1 DataFrame?如何从 df2 DataFrame 中获取与 df1 DataFrame 中的日期匹配的日期索引? I need to do this for each value in df1.我需要对 df1 中的每个值执行此操作。

Try to setup a MRE :尝试设置一个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

Swap current index of df2 with date2 columns and map the series to date1 column of df1 :df2的当前索引与date2列和 map 系列交换到df1date1列:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM