将CSV文件拆分为多个文件排序我的列

klh5stk1  于 2023-03-15  发布在  其他
关注(0)|答案(2)|浏览(163)

嗨,我是一个Python新手,我想做一个程序来分割成多个csv文件我的csv文件
文件看起来像这样:
main.csv

Name;Lieferung;Name;Ort;Postleitzahl
somename;60072470;somename;someadress;83620
somename;60071938;somename;someadress;48691
somename;60072194;somename;someadress;13595
somename;60072194;somename;someadress;13595
somename;60072511;somename;someadress;82140

我希望代码自动创建多个csv文件分组Lieferung:
60072470.csv

somename;60072470;somename;someadress;83620

60071938.csv

somename;60071938;somename;someadress;48691

60072194.csv

somename;60072194;somename;someadress;13595
somename;60072194;somename;someadress;13595

60072511.csv

somename;60072511;somename;someadress;82140

有谁能帮帮我吗,我做了很多研究,但我做不到
THX a Lot

dwbf0jvd

dwbf0jvd1#

import csv

data = {}

with open("input.csv", newline="") as file:
    reader = csv.reader(file, delimiter=";")
    header = next(reader)
    for row in reader:
        data.setdefault(row[1], [])
        data[row[1]].append(row)

for name, row in data.items():
    with open(f"{name}.csv", "w", newline="") as file:
        writer = csv.writer(file, delimiter=";")
        writer.writerow(header)
        writer.writerows(row)
jtoj6r0c

jtoj6r0c2#

试试这个:

for Lieferung in df.Lieferung.unique():
    df[df.Lieferung == Lieferung].to_csv(str(Lieferung)+'.csv')

首先迭代唯一的Lieferung值(打印df.Lieferung.unique()的输出,看看它做了什么),然后使用这些值只选择相关的数据子集(df[df.Lieferung == Lieferung]),可以使用Lieferung将这些数据导出到csv以创建文件名。

相关问题