1

我有一个数据框,其中包含无用的列名,我想将其转换为日期时间。当前列名是

Index([Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median, Market Median], dtype=object)

我试图将它们变成日期时间名称

cols = pd.date_range(start='2004-02-28', end='2013-05-31', freq='Q-NOV')
df.columns = cols

但我得到了错误

Exception: Reindexing only valid with uniquely valued Index objects

cols似乎是一个有效的索引:

<class 'pandas.tseries.index.DatetimeIndex'>
[2004-02-29 00:00:00, ..., 2013-05-31 00:00:00]
Length: 38, Freq: Q-NOV, Timezone: None

所以我不确定这个问题。我也不认为需要用唯一对象命名列,因此我正在尝试做的事情可能存在更根本的问题。

谢谢你的尽心帮助。

4

2 回答 2

2

这是一个错误(如@Andy Hayden 所述),并在即将发布的 0.11.1 中修复(很快就会发布)

In [11]: df = DataFrame([[1,1,1,5],[1,1,2,5],[2,1,3,5]],columns=['a','a','a','a'])

In [12]: idx = date_range('20130101',periods=4,freq='Q-NOV')

In [13]: df = DataFrame([[1,1,1,5],[1,1,2,5],[2,1,3,5]],columns=['a','a','a','a'])

In [14]: df.columns = idx

In [15]: df
Out[15]: 
   2013-02-28  2013-05-31  2013-08-31  2013-11-30
0           1           1           1           5
1           1           1           2           5
2           2           1           3           5
于 2013-05-23T11:27:16.813 回答
1

一种迂回的方式是reset_index置:

In [1]: df = pd.DataFrame(np.random.randn(3, 2), columns=['A', 'A'])

In [2]: df
Out[2]:
          A         A
0  0.210915  1.698726
1 -1.423380 -0.861011
2 -0.895981  0.192910

In [3]: df = df.T.reset_index(drop=True).T

In [4]: df
Out[4]:
          0         1
0  0.210915  1.698726
1 -1.423380 -0.861011
2 -0.895981  0.192910

这样你就有了一个唯一值的索引,并且可以根据你的建议更改列。
这感觉像是一种解决方法......

于 2013-05-23T11:01:31.187 回答