Python Can';重新排序列数据
我有数据帧而不是序列。如果我使用Python Can';重新排序列数据,python,pandas,dataframe,Python,Pandas,Dataframe,我有数据帧而不是序列。如果我使用len(df.columns),我的数据有3586列。如何重新排列数据序列 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
len(df.columns)
,我的数据有3586列。如何重新排列数据序列
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(排序(df.columns),axis=1)
(基于这个问题),但仍然不起作用
谢谢首先获取所有不带模式的列
V
+number
,方法是使用过滤,然后按排序所有其他值,将它们相加并传递到-首先获取第一个位置中所有非数字不匹配的列,然后对V
+number
列进行排序:
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
使用
data.reindex\u axis(已排序的(data.columns,key=lambda x:float(x[1:]),axis=1)
在您发布的类似答案中,并且已排序的(df.columns)
将基于字符串而不是基于int
,对列表进行排序,因为您有V
@Nihal-我遇到一个错误无法将字符串转换为浮点:“ac”
什么是ac
??在您的数据帧中?你能不能把print(list(df.columns))
@Nihal-我用了print(list(df.columns))
的输出贴出来,结果是ID和所有带数字但不带顺序的“V”。我不知道空调从哪里来