假设我们有以下 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 dtype
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,因为,AFAIK,如果其中一些属于 PeriodIndex dtype,则 Pandas DF 不能有混合列 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
用于合并 DF 的列 dtypes:
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')