将 pandas 中的日期时间列与另一个日期时间列和 return 索引匹配
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']]
但是这一行抛出以下错误:
Can only compare identically-labeled series objects.
我也试过使用索引函数如下:
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
列交换并将该系列映射到 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
我有两个 DataFrame - df1 和 df2。它们都包含一个日期时间列,比如 date1 和 date2。我想将 date1 列的每个值与 date2 匹配并将索引存储在新列中。我正在尝试以下代码:
df1['location'] = df2.loc[df1['date1'] == df2['date2']]
但是这一行抛出以下错误:
Can only compare identically-labeled series objects.
我也试过使用索引函数如下:
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
列交换并将该系列映射到 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