假设我们有以下的DF:
In [44]: df1
Out[44]:
1996Q2 2000Q3 2010Q4
0 1.5 3.5 1.000000
1 22.0 38.5 2.000000
2 15.0 35.0 4.333333
In [45]: df1.columns
Out[45]: PeriodIndex(['1996Q2', '2000Q3', '2010Q4'], dtype='period[Q-DEC]', freq='Q-DEC')
注意:df1.columns
是PeriodIndex
D型的
In [46]: df2
Out[46]:
a b c
0 a1 b1 c1
1 a2 b2 c2
2 a3 b3 c3
In [47]: df2.columns
Out[47]: Index(['a', 'b', 'c'], dtype='object')
merge
和join
将返回:ValueError: can only call with other PeriodIndex-ed objects
的,据我所知,熊猫DF不能有如果其中一些是PeriodIndex
dtype:
In [48]: df1.join(df2)
...
skipped
...
ValueError: can only call with other PeriodIndex-ed objects
merge
抛出同样的异常:
In [54]: pd.merge(df1, df2, left_index=True, right_index=True)
...
skipped
...
ValueError: can only call with other PeriodIndex-ed objects
因此,我们将不得不df1.columns
转换为字符串:
In [49]: df1.columns = df1.columns.values.astype(str)
In [50]: df1.columns
Out[50]: Index(['1996Q2', '2000Q3', '2010Q4'], dtype='object')
现在join
和merge
将工作:
In [51]: df1.join(df2)
Out[51]:
1996Q2 2000Q3 2010Q4 a b c
0 1.5 3.5 1.000000 a1 b1 c1
1 22.0 38.5 2.000000 a2 b2 c2
2 15.0 35.0 4.333333 a3 b3 c3
In [52]: pd.merge(df1, df2, left_index=True, right_index=True)
Out[52]:
1996Q2 2000Q3 2010Q4 a b c
0 1.5 3.5 1.000000 a1 b1 c1
1 22.0 38.5 2.000000 a2 b2 c2
2 15.0 35.0 4.333333 a3 b3 c3
列dtypes
的合并DF:
In [58]: df1.join(df2).columns
Out[58]: Index(['1996Q2', '2000Q3', '2010Q4', 'a', 'b', 'c'], dtype='object')
如果您需要df1.columns
为PeriodIndex
合并完成后 - 你可以节省df1.columns
在转换之前和设置回你与合并/加入完成后:
In [60]: df1.columns
Out[60]: PeriodIndex(['1996Q2', '2000Q3', '2010Q4'], dtype='period[Q-DEC]', freq='Q-DEC')
In [61]: cols_saved = df1.columns
In [62]: df1.columns = df1.columns.values.astype(str)
In [63]: df1.columns
Out[63]: Index(['1996Q2', '2000Q3', '2010Q4'], dtype='object')
# merging (joining) or doing smth else here ...
In [64]: df1.columns = cols_saved
In [65]: df1.columns
Out[65]: PeriodIndex(['1996Q2', '2000Q3', '2010Q4'], dtype='period[Q-DEC]', freq='Q-DEC')
你能后降低的样品([mvce(http://stackoverflow.com/help/mcve ))你的两个帧的数据?我认为你的代码绝对没有问题(也就是说,如果df3和df2确实是第1帧和第2帧) –