以CSV格式重新排序列 [英] Reordering columns in CSV

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

问题描述

问题已过帐,但要求没有正确传达。我有一个有超过1000列的csv文件:

Question has been posted before but the requirements were not properly conveyed. I have a csv file with more than 1000 columns:

A   B   C   D ....  X   Y   Z
1   0   0.5 5 ....  1   7   6
2   0   0.6 4 ....  0   7   6
3   0   0.7 3 ....  1   7   6
4   0   0.8 2 ....  0   7   6

这里X,Y和Z是999,1000,10001列,A,B,C ,D是第1,第2,第3和第4。我需要对列进行重新排序,以便它给我以下。

Here X , Y and Z are the 999, 1000, 10001 column and A, B, C , D are the 1st,2nd,3rd and 4th. I need to reorder the columns in such a way that it gives me the following.

D   Y   Z   A   B   C   ....X
5   7   6   1   0   0.5 ....1
4   7   6   2   0   0.6 ....0
3   7   6   3   0   0.7 ....1
2   7   6   4   0   0.8 ....0

第4列成为第1,1000列,第1001列成为2nd第三和其他列相应地向右移位。

that is 4th column becomes the 1st, 1000 and 1001th column becomes 2nd and 3rd and the other columns are shifted right accordingly.

推荐答案

因此,问题是如何以自定义方式对列进行重新排序。

So the question is how to reorder your columns in a custom way.

例如,您有以下DF,并且您想以下列方式(索引)重新排序列:

For example you have the following DF and you want to reorder your columns in the following way (indices):

5,3,rest ...

5, 3, rest...

DF

In [82]: df
Out[82]:
   A  B    C  D  E  F  G
0  1  0  0.5  5  1  7  6
1  2  0  0.6  4  0  7  6
2  3  0  0.7  3  1  7  6
3  4  0  0.8  2  0  7  6

In [83]: cols = df.columns.tolist()

In [84]: cols
Out[84]: ['A', 'B', 'C', 'D', 'E', 'F', 'G']


b $ b

重新排序:

reordered:

In [88]: cols = [cols.pop(5)] + [cols.pop(3)] + cols

In [89]: cols
Out[89]: ['F', 'D', 'A', 'B', 'C', 'E', 'G']

In [90]: df[cols]
Out[90]:
   F  D  A  B    C  E  G
0  7  5  1  0  0.5  1  6
1  7  4  2  0  0.6  0  6
2  7  3  3  0  0.7  1  6
3  7  2  4  0  0.8  0  6

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

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