Pandas: 无法合并两个日期列
Pandas: Unable to merge on two date columns
我有两个数据框,如下所示:
df1:
Date Multiplier
0 1995-01-01 5.248256
1 1995-02-01 5.262376
2 1995-03-01 5.255998
3 1995-04-01 5.215762
4 1995-05-01 5.207806
df2:
PRICE Date
0 77500 1995-01-01
1 60000 1995-01-01
2 39250 1995-01-01
3 51250 1995-01-01
4 224950 1995-01-01
两个日期列都是使用 pd.to_datetime()
方法创建的,并且在使用 df1.Date.dtype
和 df2.Date.dtype
时它们都应该具有 <M8[ns]
数据类型。但是,当尝试将数据帧与 pd.merge(df,hpi,how="left",on="Date")
合并时,出现错误:
ValueError: You are trying to merge on object and datetime64[ns] columns. If you wish to proceed you should use pd.concat
尝试将 df1
的 Date
列转换为 datetime64
先检查dtypes
:
>>> df1.dtypes
Date object # <- Not a datetime
Multiplier float64
dtype: object
>>> df2.dtypes
PRICE int64
Date datetime64[ns] # <- Right dtype
dtype: object
转换并合并:
df1['Date'] = pd.to_datetime(df1['Date'])
out = pd.merge(df1, df2,how='left',on='Date')
我有两个数据框,如下所示:
df1:
Date Multiplier
0 1995-01-01 5.248256
1 1995-02-01 5.262376
2 1995-03-01 5.255998
3 1995-04-01 5.215762
4 1995-05-01 5.207806
df2:
PRICE Date
0 77500 1995-01-01
1 60000 1995-01-01
2 39250 1995-01-01
3 51250 1995-01-01
4 224950 1995-01-01
两个日期列都是使用 pd.to_datetime()
方法创建的,并且在使用 df1.Date.dtype
和 df2.Date.dtype
时它们都应该具有 <M8[ns]
数据类型。但是,当尝试将数据帧与 pd.merge(df,hpi,how="left",on="Date")
合并时,出现错误:
ValueError: You are trying to merge on object and datetime64[ns] columns. If you wish to proceed you should use pd.concat
尝试将 df1
的 Date
列转换为 datetime64
先检查dtypes
:
>>> df1.dtypes
Date object # <- Not a datetime
Multiplier float64
dtype: object
>>> df2.dtypes
PRICE int64
Date datetime64[ns] # <- Right dtype
dtype: object
转换并合并:
df1['Date'] = pd.to_datetime(df1['Date'])
out = pd.merge(df1, df2,how='left',on='Date')