Skip to content
Advertisement

Matching datetime column in pandas with another datetime column and return index

I have two DataFrames – df1 and df2. Both of them contain a datetime column, say date1 and date2. I want to match each value of date1 column to date2 and store the index in a new column. 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:

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? I need to do this for each value in df1.

Advertisement

Answer

for i, row in df2.iterrows():
    df1.loc[df1['date1'] == df2.at[i, 'date2'], 'location'] = i
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement