Python 将两个数据帧与timeseries索引合并
我有两个数据帧,我想合并/连接在一起 例如:Python 将两个数据帧与timeseries索引合并,python,python-3.x,pandas,join,merge,Python,Python 3.x,Pandas,Join,Merge,我有两个数据帧,我想合并/连接在一起 例如: #required packages import os import pandas as pd import numpy as np import datetime as dt # create sample time series dates1 = pd.date_range('1/1/2000', periods=4, freq='10min') dates2 = dates1 column_names = ['A','B','C'] df1
#required packages
import os
import pandas as pd
import numpy as np
import datetime as dt
# create sample time series
dates1 = pd.date_range('1/1/2000', periods=4, freq='10min')
dates2 = dates1
column_names = ['A','B','C']
df1 = pd.DataFrame(np.random.randn(4, 3), index=dates1,
columns=column_names)
df2 = pd.DataFrame(np.random.randn(4, 3), index=dates2,
columns=column_names)
df3 = df1.merge(df2, how='outer', left_index=True, right_index=True, suffixes=('_x', '_y'))
在这里,我希望以以下方式合并这两个数据集(注意列的顺序):
我希望通过创建多索引数据帧或为第二个索引创建列来保留这两个数据帧索引。使用merge_ordered而不是merge或join会更容易吗
非常感谢您提供的任何帮助。我想您不想合并:
In [11]: pd.concat([df1, df2], keys=["df1", "df2"], axis=1)
Out[11]:
df1 df2
A B C A B C
2000-01-01 00:00:00 1.621737 0.093015 -0.698715 0.319212 1.021829 1.707847
2000-01-01 00:10:00 0.780523 -1.169127 -1.097695 -0.444000 0.170283 1.652005
2000-01-01 00:20:00 1.560046 -0.196604 -1.260149 0.725005 -1.290074 0.606269
2000-01-01 00:30:00 -1.074419 -2.488055 -0.548531 -1.046327 0.895894 0.423743
使用concat
pd.concat([df1.reset_index().add_suffix('_x'),\
df2.reset_index().add_suffix('_y')], axis = 1)\
.set_index(['index_x', 'index_y'])
A_x B_x C_x A_y B_y C_y
index_x index_y
2000-01-01 00:00:00 2000-01-01 00:00:00 -1.437311 -1.414127 0.344057 -0.533669 -0.260106 -1.316879
2000-01-01 00:10:00 2000-01-01 00:10:00 0.662025 1.860933 -0.485169 -0.825603 -0.973267 -0.760737
2000-01-01 00:20:00 2000-01-01 00:20:00 -0.300213 0.047812 -2.279631 -0.739694 -1.872261 2.281126
2000-01-01 00:30:00 2000-01-01 00:30:00 1.499468 0.633967 -1.067881 0.174793 1.197813 -0.879132
merge
确实会合并这两个索引
在合并之前,您可以在df2
中创建额外的列:
df2["index_2"]=df2.index
这将在最终结果中创建一列,该列将是df2
中的索引值
请注意,此列与索引不同的唯一情况是当元素未出现在
df2
中时,在这种情况下,它将为空,因此我不确定我是否理解您在这方面的最终目标。我认为这与我想要的接近,但列的顺序与我想要的不完全一样。我需要一个月一个月一个月的时间。。。等等有没有办法按这种方式对列进行排序?也许还有一个排序函数?@MooseDrool,你可以使用df.sort\u索引(axis=1,inplace=True),这很有意义!
df2["index_2"]=df2.index