代码之家  ›  专栏  ›  技术社区  ›  swifty

Pandas-反转和指定列名不起作用

  •  1
  • swifty  · 技术社区  · 8 年前

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

    它不起作用,列名不变。

    感谢您的帮助-谢谢。

    1 回复  |  直到 8 年前
        1
  •  2
  •   cs95 abhishek58g    8 年前

    做一个小的子列表反转和重新分配:

    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