ValueError:只能使用其他PeriodIndexed对象调用

2024-03-28 15:13:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图合并两个数据帧在一起。具有讽刺意味的是,它们一开始是作为同一个数据帧的一部分,但我正在迈出第一步——有时是在错误的方向上。 第1帧如下所示:


Int64Index: 10730 entries, 0 to 10729
Data columns (total 6 columns):
RegionID      10730 non-null int64
RegionName    10730 non-null object
State         10730 non-null object
Metro         10259 non-null object
CountyName    10730 non-null object
SizeRank      10730 non-null int64
dtypes: int64(2), object(4)

第二帧如下:

^{pr2}$

请注意,索引的类型相同,甚至具有相同的行数。
我正在尝试将数据帧合并到一起,如下所示:

df4 = pd.merge(df3, df2, how='inner', left_index=True, right_index=True)

我得到的错误是:

ValueError: can only call with other PeriodIndex-ed objects

2016Q1和第二个dataframe中类似名称的列是Period类型的,但是我没有合并它们——我想只要索引排成一行,merge就可以工作了?我做错什么了?在


Tags: columns数据true类型indexobject错误merge
2条回答

实际上,我也遇到了同样的问题,也得到了整数列。在

而不是

df1.columns = df1.columns.values.astype(str)

我用过

^{pr2}$

希望这有帮助

假设我们有以下DFs:

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数据类型

^{pr2}$

mergejoin将返回:ValueError: can only call with other PeriodIndex-ed objects因为,AFAIK,Pandas DF不能有混合列数据类型,如果其中一些是PeriodIndex数据类型:

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和{}将工作:

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列:

In [58]: df1.join(df2).columns
Out[58]: Index(['1996Q2', '2000Q3', '2010Q4', 'a', 'b', 'c'], dtype='object')

如果合并完成后需要df1.columns作为PeriodIndex,可以在转换它们之前保存{},并在完成合并/合并后将其设置回:

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')

相关问题 更多 >