无法使用ix更改pandas数据帧的特定列范围的名称

时间:2017-02-25 13:07:37

标签: python pandas dataframe

我的目标是更改原始名称为日期时间类型的列的名称(11.10.2015 00:13)(但存储的列值为整数)。例如,我有6个这样的列,我想用这个列表[6,5,5,3,2,1]中的相应数字替换每个列名。这是我的代码的相关部分:

count_datetime = 6
test = pd.DataFrame(columns=['userid', '12.10.2012 15:30', '02.10.2012 15:30',
                             '22.10.2012 15:30', '11.10.2012 15:30',
                             '15.10.2012 15:30', '20.10.2012 15:30', 'category'])
print test    
test.ix[:,1:count_datetime].columns = range(10, 15)[::-1]
print test

这不做任何更改,并保留所有原始列名。

我想获得的是拥有以下列名称:用户ID,6,5,4,3,2,1,类别

但是,如果我摆脱ix并尝试更改所有列名:

test.columns = range(10, 18)[::1]

然后它的工作原理。但是,这不是我想要的。我想只更新日期时间列名

的那些

关于我在这里缺少什么的想法?

1 个答案:

答案 0 :(得分:1)

试试这个:

In [12]: test.columns
Out[12]: Index(['userid', '12.10.2012 15:30', '02.10.2012 15:30', '22.10.2012 15:30', '11.10.2012 15:30', '15.10.2012 15:30', '20.10.2012 15
:30', 'category'], dtype='object')

In [13]: cols = test.columns.tolist()

In [14]: test.columns = cols[:1] + list(map(str, np.arange(count_datetime, 0, -1))) + cols[count_datetime+1:]

In [15]: test.columns
Out[15]: Index(['userid', '6', '5', '4', '3', '2', '1', 'category'], dtype='object')

In [16]: test
Out[16]:
Empty DataFrame
Columns: [userid, 6, 5, 4, 3, 2, 1, category]
Index: []