pandas to_datetime()然后在DateTime索引上concat() [英] pandas to_datetime() then concat() on DateTime Index
本文介绍了 pandas to_datetime()然后在DateTime索引上concat()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用concat
在其DateTime索引上合并2个DataFrame,但是它没有按我预期的那样工作.我从文档中的示例中复制了一些代码. a>对于此示例:
I'm trying to merge 2 DataFrames using concat
, on their DateTime Index, but it's not working as I expected. I copied some of this code from the example in the documentation for this example:
import pandas as pd
df = pd.DataFrame({'year': [2015, 2016],
'month': [2, 3],
'day': [4, 5],
'value': [444,555]})
df.set_index(pd.to_datetime(df.loc[:,['year','month','day']]),inplace=True)
df.drop(['year','month','day'],axis=1,inplace=True)
df2 = pd.DataFrame(data=[222,333],
index=pd.to_datetime(['2015-02-04','2016-03-05']))
pd.concat([df,df2])
Out[1]:
value 0
2015-02-04 444.0 NaN
2016-03-05 555.0 NaN
2015-02-04 NaN 222.0
2016-03-05 NaN 333.0
为什么它不能在索引上识别相同的日期并相应地合并?我验证了两个索引都是DateTime:
Why isn't it recognizing the same dates on the index and merging accordingly? I verified that both Indexes are DateTime:
df.index
Out[2]: DatetimeIndex(['2015-02-04', '2016-03-05'], dtype='datetime64[ns]', freq=None)
df2.index
Out[3]: DatetimeIndex(['2015-02-04', '2016-03-05'], dtype='datetime64[ns]', freq=None)
谢谢.
推荐答案
pass axis=1
to concatenate column-wise:
In [7]:
pd.concat([df,df2], axis=1)
Out[7]:
value 0
2015-02-04 444 222
2016-03-05 555 333
或者,您可以join
In [5]:
df.join(df2)
Out[5]:
value 0
2015-02-04 444 222
2016-03-05 555 333
或merge
d:
In [8]:
df.merge(df2, left_index=True, right_index=True)
Out[8]:
value 0
2015-02-04 444 222
2016-03-05 555 333
这篇关于 pandas to_datetime()然后在DateTime索引上concat()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文