Pandas pd.concat()和pd.merge()之间的区别以及为什么会得到错误的输出?
我面临着两个需要连接的数据帧的困难。我通常应用pd.merge()。但在这种情况下,我得到一个ValueError,建议使用pd.concat()。因此,我的情况是: 我有两个数据帧,df1和df2,下面是它们的索引Pandas pd.concat()和pd.merge()之间的区别以及为什么会得到错误的输出?,pandas,dataframe,datetime,merge,concat,Pandas,Dataframe,Datetime,Merge,Concat,我面临着两个需要连接的数据帧的困难。我通常应用pd.merge()。但在这种情况下,我得到一个ValueError,建议使用pd.concat()。因此,我的情况是: 我有两个数据帧,df1和df2,下面是它们的索引 In [15]: df1.index Out[15]: DatetimeIndex(['2019-11-03 00:00:00', '2019-11-03 01:00:00', '2019-11-03 02:00:00', '2019-11-03 0
In [15]: df1.index
Out[15]:
DatetimeIndex(['2019-11-03 00:00:00', '2019-11-03 01:00:00',
'2019-11-03 02:00:00', '2019-11-03 03:00:00',
...
'2019-11-12 11:00:00', '2019-11-12 12:00:00',
'2019-11-12 13:00:00', '2019-11-12 14:00:00'],
dtype='datetime64[ns]', name='datetime', length=231, freq=None)
In [16]: df2.index
Out[16]:
Index(['2019-11-03 00:00:00', '2019-11-04 00:00:00',
'2019-11-05 00:00:00', '2019-11-06 00:00:00',
'2019-11-07 00:00:00', '2019-11-08 00:00:00',
'2019-11-09 00:00:00', '2019-11-10 00:00:00',
'2019-11-11 00:00:00', '2019-11-12 00:00:00'],
dtype='object', name='datetime')
当我试图通过merged=pd.merge(df1,df2,left_on=['datetime'],right_on=['datetime'],how='left')来合并两个数据帧时,
我收到一条消息ValueError:您试图在datetime64[ns]和对象列上合并。如果您希望继续,应使用pd.concat
请允许我也向您介绍这两个数据帧
temperatures = [c for c in df1 if c.startswith('temp')]
df1['temp_mean']=df1[temperatures].mean(axis=1)
In [6]: df1.head(3)
Out[6]:
location temperature1 temperature2 wind rain temp_mean
datetime
2019-10-03 00:00:00 HK 18.72 18.78 SW 0.0 18.75
2019-10-03 01:00:00 HK 18.63 18.67 SW 0.1 18.65
2019-10-03 02:00:00 HK 18.29 18.31 SW 0.3 18.30
In [7]:df2
Out[7]:
values
datetime
2019-11-03 00:00:00 0.154286
2019-11-04 00:00:00 -5.094286
2019-11-05 00:00:00 1.432857
2019-11-06 00:00:00 0.227143
2019-11-07 00:00:00 0.160000
2019-11-08 00:00:00 1.300000
2019-11-09 00:00:00 0.308571
2019-11-10 00:00:00 0.442857
2019-11-11 00:00:00 0.241429
2019-11-12 00:00:00 NaN
显然,通过合并这两个数据帧,我期望df2的列“值”将在最后加入df1,并且随时00:00:00'将用NaN填充,并且值将放置在时间=='00:00:00'处。由于我得到了使用pd.concat()的错误和建议,我键入concated=pd.concat([df1,df2],axis=1,join='outer',ignore_index=False)
并得到下面的输出,其中列“values”在那里,但完全为空(在任何时候我都得到NaNs)
我不明白我在这里做错了什么,也不明白我如何才能做到这一点
一开始,我不明白为什么pd.merge()
不能处理我的数据帧,然后我就不明白为什么pd.concat()
看不到这些值
此时,您的帮助将非常有价值,因此提前感谢您。我认为您需要使用left\u index=True
和right\u index=True
进行匹配,因为这两个DataFrame
中的DatetimeIndex
匹配:
#convert to DatetimeIndex
df2.index = pd.to_datetime(df2.index)
df = pd.merge(df1, df2, left_index=True, right_index=True)
您正在尝试合并具有不同数据类型的datetime列 df1:dtype='datetime64[ns]' df2:dtype='object' 解决方案:使用, .dt.strftime(转换为字符串) 或
pd.to_datetime(转换为datetime数据类型)。。。对成功了。非常感谢你!因此,当datetime是索引时,我必须在方法中应用特定的参数。
#convert to DatetimeIndex
df2.index = pd.to_datetime(df2.index)
df = pd.merge(df1, df2, left_index=True, right_index=True)