Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

python - Reordering columns in 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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

columns

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...