我有一个具有6000列的df,其中一个子集(1500列)的列名被错误地颠倒了。
我可以像这样拉出子集:
orderbook.loc[:,'ask_price_1500':'ask_price_1'].columns
并获得cols:
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]
它无效,列名不变。
感谢您的帮助-谢谢。
答案 0 :(得分:2)
进行一些子列表冲销和重新分配:
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