Jos*_*h D 4 python datetime pandas
我正在尝试使用concat, 在它们的日期时间索引上合并 2 个数据帧,但它没有按我预期的那样工作。我从这个例子的文档中的例子中复制了一些代码:
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
Run Code Online (Sandbox Code Playgroud)
为什么它不能识别索引上的相同日期并相应地合并?我验证了两个索引都是 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)
Run Code Online (Sandbox Code Playgroud)
谢谢。
传递axis=1以按列连接:
In [7]:
pd.concat([df,df2], axis=1)
Out[7]:
value 0
2015-02-04 444 222
2016-03-05 555 333
Run Code Online (Sandbox Code Playgroud)
或者你可以join编辑:
In [5]:
df.join(df2)
Out[5]:
value 0
2015-02-04 444 222
2016-03-05 555 333
Run Code Online (Sandbox Code Playgroud)
或merged:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8041 次 |
| 最近记录: |