Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将csv拆分为多个csv_Python_Pandas_Csv - Fatal编程技术网

Python 将csv拆分为多个csv

Python 将csv拆分为多个csv,python,pandas,csv,Python,Pandas,Csv,我正在尝试根据一些条件将csv拆分为多个文件。例如,我有一个csv,如下所示: ID Timestamp Product Price XX T1 P1 10 XX T2 P1 11 XX T2 P1 12 XX T3 P1 13 XX T3 P1 14 YY T1 P1

我正在尝试根据一些条件将csv拆分为多个文件。例如,我有一个csv,如下所示:

ID    Timestamp  Product  Price
XX      T1         P1       10  
XX      T2         P1       11
XX      T2         P1       12
XX      T3         P1       13
XX      T3         P1       14
YY      T1         P1       20
YY      T1         P2       25
预期产出:

文件1:XX_P1_file1.csv

ID    Timestamp  Product  Price
XX      T1         P1.      10  
XX      T2         P1.      11
XX      T3         P1       13
ID    Timestamp  Product  Price
YY      T1         P1       20
ID    Timestamp  Product  Price
YY      T1         P2       25
文件2:XX_P1_file2.csv

ID    Timestamp  Product  Price
XX      T2         P1       12
XX      T3         P1       14
文件3:YY_P1_file1.csv

ID    Timestamp  Product  Price
XX      T1         P1.      10  
XX      T2         P1.      11
XX      T3         P1       13
ID    Timestamp  Product  Price
YY      T1         P1       20
ID    Timestamp  Product  Price
YY      T1         P2       25
文件4:YY_P2_file1.csv

ID    Timestamp  Product  Price
XX      T1         P1.      10  
XX      T2         P1.      11
XX      T3         P1       13
ID    Timestamp  Product  Price
YY      T1         P1       20
ID    Timestamp  Product  Price
YY      T1         P2       25
目前,代码只查找键(ID、Product),我想在“Timestamp”周围创建一个条件以获得所需的结果,我发现添加它很困难。 代码:


任何帮助都将不胜感激。谢谢

使用
.cumcount
创建一个“文件”列就可以了。此列稍后将用于帮助动态创建文件名,然后在发送到多个动态命名的文件之前删除。循环中的csv文件,两列上有
.groupby
,这是将数据集和附带的文件名分组为动态文件所必需的。您不需要为“Product”列指定任何逻辑,因为“Timestamp”重置为1,所以它将被标记为必须进入新文件

import pandas as pd
df = pd.read_csv('your_filename.csv')
df['File'] = df.groupby(['ID', 'Timestamp']).cumcount()+1
for (i,f), x in df.groupby(['ID', 'File']):
    x.drop('File', axis=1).to_csv(f'{i}_T{f}_file{f}.csv', index=False)
df
输出:

   ID Timestamp Product  Price  File
0  XX        T1      P1     10     1
1  XX        T2      P1     11     1
3  XX        T3      P1     13     1

   ID Timestamp Product  Price  File
2  XX        T2      P1     12     2
4  XX        T3      P1     14     2

   ID Timestamp Product  Price  File
5  YY        T1      P1     20     1

   ID Timestamp Product  Price  File
6  YY        T1      P2     25     2

下面是对代码的一个修改。它跟踪ID/产品密钥的实例,以将时间戳指向正确的文件。它假定您的文件已经按排序键排序(这是
itertools.groupby
的要求),但如果需要,您可以使用
csvin=sorted(list(csv.DictReader(filein)),key=sortkey)对所有行进行预读和排序

import csv
import itertools
import operator

headers = ['ID', 'Timestamp', 'Product', 'Price']
sortkey = operator.itemgetter('ID', 'Product', 'Timestamp')
files = {}

with open('input.csv', newline='') as filein:
    csvin = csv.DictReader(filein)
    for (id_, product, timestamp), group in itertools.groupby(csvin, key=sortkey):
        for instance, row in enumerate(group, 1):
            key = id_, product, instance
            if key not in files:
                filename = f'{id_}_{product}_file{instance}.csv'
                print(f'Starting {filename}')
                fileout = open(filename, 'w', newline='')
                writer = csv.DictWriter(fileout, headers)
                writer.writeheader()
                files[key] = fileout, writer
            files[key][1].writerow(row)

print(f'Closing {len(files)} output files')
for openfile, _ in files.values():
    openfile.close()
输出:

Starting XX_P1_file1.csv
Starting XX_P1_file2.csv
Starting YY_P1_file1.csv
Starting YY_P2_file1.csv
Closing 4 output files

根据您的输入,文件与您所需的输出匹配。

Hi-Jithu,您是否考虑过使用?如果我是你,我会使用pandas.read_csv()将csv文件加载到pandas数据框中,使用布尔掩码将数据过滤到单独的数据框中,然后使用DataFrame.to_csv()保存结果。分离时间戳的条件是什么?看起来您希望特定ID/产品的T1/T2/T3的第一个实例转到文件1,第二个实例转到文件2。还有更多的例子吗?您的数据文件是否如图所示进行了预排序?对于这个问题,我绝对推荐pandas。除了能够得到一个更具python风格的解决方案外,考虑到矢量化的方法,在pandas中应该会更有效。Jithu有任何解决方案适合您吗?你能通过按下答案旁边的复选标记来接受最好的答案吗?谢谢大家的帮助。非常感谢!