熊猫 - 度假村位置

时间:2017-06-07 06:16:37

标签: python pandas

我有一个熊猫框架。当我打印列(如下所示)时,我的列发生故障。有没有办法只对前30列进行排序,使它们按顺序排列(30,60,90 ... 900)?

[in]   df.columns

[out]  Index(['120', '150', '180', '210', '240', '270', '30', '300', '330', '360',
   '390', '420', '450', '480', '510', '540', '570', '60', '600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870', '90', '900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'],
  dtype='object')

固定框架如下:

[out]  Index(['30','60','90,'120', '150', '180', '210', '240', '270','300', '330', '360',
   '390', '420', '450', '480', '510', '540', '570','600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870','900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'],
  dtype='object')

2 个答案:

答案 0 :(得分:1)

如果你知道这些列的名称是30到900,是30的倍数,你可以像这样明确地生成:

c = [str(i) for i in range(30, 901, 30)]

然后将其添加到其他列:

c = c + ['Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0']

然后您应该能够以df[c]

的形式访问它

答案 1 :(得分:0)

您需要选择第一列名称,转换为int并进行排序。然后,如有必要,请转换回str并使用reindex_axis

np.sort(df.columns[:30].astype(int)).astype(str).tolist() +
             df.columns[30:].tolist()

样品:

df = pd.DataFrame(np.arange(36).reshape(1,-1),
   columns=['120', '150', '180', '210', '240', '270', '30', '300', 
   '330', '360','390', '420', '450', '480', '510', '540', '570', '60', '600', '630',
   '660', '690', '720', '750', '780', '810', '840', '870', '90', '900',
   'Item', 'Price', 'Size', 'Time', 'Type', 'Unnamed: 0'])


print (df)
   120  150  180  210  240  270  30  300  330  360     ...      840  870  90  \
0    0    1    2    3    4    5   6    7    8    9     ...       26   27  28   

   900  Item  Price  Size  Time  Type  Unnamed: 0  
0   29    30     31    32    33    34          35  

[1 rows x 36 columns]


df = df.reindex_axis(np.sort(df.columns[:30].astype(int)).astype(str).tolist() + 
                     df.columns[30:].tolist(), axis=1)
print (df)
   30  60  90  120  150  180  210  240  270  300     ...      810  840  870  \
0   6  17  28    0    1    2    3    4    5    7     ...       25   26   27   

   900  Item  Price  Size  Time  Type  Unnamed: 0  
0   29    30     31    32    33    34          35  

[1 rows x 36 columns]