Python - 重新排序 csv 中的列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33001490/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python - re-ordering columns in a csv
提问by JJ1603
I have a bunch of csv files with the same columns but in different order. We are trying to upload them with SQL*Plus but we need the columns with a fixed column arrange.
我有一堆具有相同列但顺序不同的 csv 文件。我们正在尝试使用 SQL*Plus 上传它们,但我们需要具有固定列排列的列。
Example
例子
required order: A B C D E F
所需订单:ABCDEF
csv file: A C D E B (sometimes a column is not in the csv because it is not available)
csv 文件:ACDEB(有时某列不在 csv 中,因为它不可用)
is it achievable with python? we are using Access+Macros to do it... but it is too time consuming
用python可以实现吗?我们是用Access+Macros来做的……但是太费时间了
PS. Sorry if anyone get upset for my English skills.
附注。对不起,如果有人对我的英语技能感到不安。
采纳答案by Josh J
You can use the csv moduleto read, reorder, and then and write your file.
您可以使用csv 模块来读取、重新排序、然后写入您的文件。
Sample File:
示例文件:
$ cat file.csv
A,B,C,D,E
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
Code
代码
import csv
with open('file.csv', 'r') as infile, open('reordered.csv', 'a') as outfile:
# output dict needs a list for new column ordering
fieldnames = ['A', 'C', 'D', 'E', 'B']
writer = csv.DictWriter(outfile, fieldnames=fieldnames)
# reorder the header first
writer.writeheader()
for row in csv.DictReader(infile):
# writes the reordered rows to the new file
writer.writerow(row)
output
输出
$ cat reordered.csv
A,C,D,E,B
a1,c1,d1,e1,b1
a2,c2,d2,e2,b2
回答by Prune
csv_in = open("<filename>.csv", "r")
csv_out = open("<filename>.csv", "w")
for line in csv_in:
field_list = line.split(',') # split the line at commas
output_line = ','.join(field_list[0], # rejoin with commas, new order
field_list[2],
field_list[3],
field_list[4],
field_list[1]
)
csv_out.write(output_line)
csv_in.close()
csv_out.close()
回答by thisismario123
You can use something similar to thisto change the order, replacing ';' with ',' in your case. Because you said you needed to do multiple .csv files, you could use the glob module for a list of your files
您可以使用类似于此的内容来更改顺序,替换 ';' 在您的情况下使用“,”。因为你说你需要做多个 .csv 文件,你可以使用 glob 模块来获取你的文件列表
for file_name in glob.glob('<Insert-your-file-filter-here>*.csv'):
#Do the work here
回答by MisterMiyagi
The csv
module allows you to read csv files with their values associated to their column names. This in turn allows you to arbitrarily rearrange columns, without having to explicitly permute lists.
该csv
模块允许您读取 csv 文件,其值与其列名相关联。这反过来又允许您任意重新排列列,而不必显式排列列表。
for row in csv.DictReader(open("foo.csv")):
print row["b"], row["a"]
2 1
22 21
Given the file foo.csv:
鉴于文件foo.csv:
a,b,d,e,f
1,2,3,4,5
21,22,23,24,25
回答by titipata
So one way to tackle this problem is to use pandas
library which can be easily install using pip
. Basically, you can download csv
file to pandas dataframe then re-order the column and save it back to csv
file. For example, if your sample.csv
looks like below:
因此,解决此问题的一种方法是使用pandas
可以轻松安装的库pip
。基本上,您可以将csv
文件下载到 Pandas 数据帧,然后对列重新排序并将其保存回csv
文件。例如,如果你sample.csv
看起来像下面这样:
A,C,B,E,D
a1,b1,c1,d1,e1
a2,b2,c2,d2,e2
Here is a snippet to solve the problem.
这是解决问题的一个片段。
import pandas as pd
df = pd.read_csv('/path/to/sample.csv')
df_reorder = df[['A', 'B', 'C', 'D', 'E']] # rearrange column here
df_reorder.to_csv('/path/to/sample_reorder.csv', index=False)