gpt4 book ai didi

python - Pandas - 反转和分配列名称不起作用

转载 作者:行者123 更新时间:2023-12-01 01:39:38 25 4
gpt4 key购买 nike

我有一个包含 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]

它没有任何效果,列名也不会改变。

感谢任何帮助 - 谢谢。

最佳答案

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

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

关于python - Pandas - 反转和分配列名称不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52030490/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com