无法重新排序列数据 [英] Can't Re-Order Columns Data

查看:82
本文介绍了无法重新排序列数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据框不是序列.如果使用len(df.columns),则我的数据有3586列.如何重新排序数据序列?

I have dataframe not sequences. if I use len(df.columns), my data has 3586 columns. How to re-order the data sequences?

ID  V1  V10 V100 V1000 V1001 V1002 ...  V990 V991 V992 V993 V994
A   1   9.0 2.9  0.0   0.0   0.0   0.0  0.0  0.0  0.0  0.0  0.0
B   1   1.2 0.1  3.0   0.0   0.0   0.0  1.0  0.0  0.0  0.0  0.0
C   2   8.6 8.0  2.0   0.0   0.0   0.0  2.0  0.0  0.0  0.0  0.0
D   3   0.0 2.0  0.0   0.0   0.0   0.0  3.0  0.0  0.0  0.0  0.0
E   4   7.8 6.6  3.0   0.0   0.0   0.0  4.0  0.0  0.0  0.0  0.0

我使用了这个df = df.reindex(sorted(df.columns), axis=1)(基于此问题

I used this df = df.reindex(sorted(df.columns), axis=1) (based on this question Re-ordering columns in pandas dataframe based on column name) but still not working.

谢谢

推荐答案

首先使用

First get all columns without pattern V + number by filtering with str.contains, then sorting all another values by Index.difference, add together and pass to DataFrame.reindex - get first all non numeric non matched columns in first positions and then sorted V + number columns:

L1 = df.columns[~df.columns.str.contains('^V\d+$')].tolist()

L2 = sorted(df.columns.difference(L1), key=lambda x: float(x[1:]))

df = df.reindex(L1 + L2, axis=1)
print (df)
   ID   V1  V10  V100  V990  V991  V992  V993  V994  V1000  V1001  V1002
A   1  9.0  2.9   0.0   0.0   0.0   0.0   0.0   0.0    0.0    0.0    0.0
B   1  1.2  0.1   3.0   1.0   0.0   0.0   0.0   0.0    0.0    0.0    0.0
C   2  8.6  8.0   2.0   2.0   0.0   0.0   0.0   0.0    0.0    0.0    0.0
D   3  0.0  2.0   0.0   3.0   0.0   0.0   0.0   0.0    0.0    0.0    0.0
E   4  7.8  6.6   3.0   4.0   0.0   0.0   0.0   0.0    0.0    0.0    0.0

这篇关于无法重新排序列数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆