设置和分配列名不起作用

2024-03-29 11:01:18 发布

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

我有一个包含6000列的df,其中一个子集(1500列)的列名被错误地颠倒了

我可以这样抽出子集:

orderbook.loc[:,'ask_price_1500':'ask_price_1'].columns

去拿可乐:

Index(['ask_price_1500', 'ask_price_1499', 'ask_price_1498', 'ask_price_1497',
       'ask_price_1496', 'ask_price_1495', 'ask_price_1494', 'ask_price_1493',
       'ask_price_1492', 'ask_price_1491',
       ...
       'ask_price_10', 'ask_price_9', 'ask_price_8', 'ask_price_7',
       'ask_price_6', 'ask_price_5', 'ask_price_4', 'ask_price_3',
       'ask_price_2', 'ask_price_1'],
      dtype='object', length=1500)

现在反转列非常容易,我只需添加[::-1]即可获得新的顺序

Index(['ask_price_1', 'ask_price_2', 'ask_price_3', 'ask_price_4',
       'ask_price_5', 'ask_price_6', 'ask_price_7', 'ask_price_8',
       'ask_price_9', 'ask_price_10',
       ...
       'ask_price_1491', 'ask_price_1492', 'ask_price_1493', 'ask_price_1494',
       'ask_price_1495', 'ask_price_1496', 'ask_price_1497', 'ask_price_1498',
       'ask_price_1499', 'ask_price_1500'],
      dtype='object', length=1500)

但是,当尝试用

orderbook.loc[:,'ask_price_1500':'ask_price_1'].columns = orderbook.loc[:,'ask_price_1500':'ask_price_1'].columns[::-1]

它没有效果,列名也不会更改

感谢您的帮助-谢谢


Tags: columnsdfindexobject顺序错误lengthprice
1条回答
网友
1楼 · 发布于 2024-03-29 11:01:18

做一点子列表反转和重新分配:

v = orderbook.columns.tolist()
# The index that comes first.
i = orderbook.columns.get_loc('ask_price_1500')
# The index that comes second.
j = orderbook.columns.get_loc('ask_price_1')
# Reverse list subslice.
v[i:j+1] = v[j:i-1:-1]
# Assign the result back to the DataFrame.
df.columns = v

相关问题 更多 >