Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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_Python 3.x_Pandas_Csv - Fatal编程技术网

使用python将csv拆分为小csv

使用python将csv拆分为小csv,python,python-3.x,pandas,csv,Python,Python 3.x,Pandas,Csv,我有一个csv(大约750MB大小)。我必须将其拆分为大小不超过30Mb的小csv c1,c2,c3,c4 1,a,1,4 2,a,1,4 3,b,1,4 4,b,1,4 5,b,1,4 6,c,1,4 约束条件是不同文件中不能有相同的c2。 (例如,一个文件中不能有一半b,另一半不能在另一个文件中) 如果C2本身的一个值大于30Mb,则将与该C2相关的数据打印到文件中 我用熊猫做同样的事;我的代码 max_size = 30 * 1000000 df = pd.read_csv("data.

我有一个
csv
(大约750MB大小)。我必须将其拆分为大小不超过30Mb的小
csv

c1,c2,c3,c4
1,a,1,4
2,a,1,4
3,b,1,4
4,b,1,4
5,b,1,4
6,c,1,4
约束条件是不同文件中不能有相同的
c2
。 (例如,一个文件中不能有一半
b
,另一半不能在另一个文件中) 如果
C2
本身的一个值大于30Mb,则将与该
C2
相关的数据打印到文件中

我用熊猫做同样的事;我的代码

max_size = 30 * 1000000
df = pd.read_csv("data.csv", low_memory=False)
unique_ac_id = pd.unique(df.C2)

counter = 1
df_arr = []
total_size = 0

for ac_id in unique_ac_id:
    df_cur = df[df.C2 == ac_id]
    size = df_cur.memory_usage(index=False, deep=True).sum()
    if size > max_size:
        print(f'{ac_id} size is more than max size allowded')

    if total_size > max_size:
        pd.concat(df_arr).to_csv(f'out/splitter_{counter}.csv', index=False)
        counter += 1
        df_arr.clear()
        total_size = 0

    df_arr.append(df_cur)
    total_size += size

if len(df_arr) > 0:
    pd.concat(df_arr).to_csv(f'out/splitter_{counter}.csv', index=False)
还有更好的方法吗?

我想你可以用

语法非常简单:

>>> import csv
>>> with open('eggs.csv', 'rb') as csvfile:
...     spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
...     for row in spamreader:
...         print ', '.join(row)
Spam, Spam, Spam, Spam, Spam, Baked Beans
Spam, Lovely Spam, Wonderful Spam
使用这种方法,我一次只读取30MB,然后将读取的内容输出到另一个csv。如果您有
行中的矢量内容
,您将能够确定每行的大小,并确定有多少行的容量约为30MB,因此希望这将帮助您开始


此外,考虑到
c2
的限制,您可能会打开多个csv,以便每个csv将包含其各自的
c2
分组。每一行都是一个向量,因此在您给出的示例中,这似乎是第二个元素。

您可以轻松地将CSV分割为大小相等的块

import pandas as pd
for i,chunk in enumerate(pd.read_csv('C:/your_path_here/main.csv', chunksize=100)):
    chunk.to_csv('chunk{}.csv'.format(i))

这个约束是不可行的。如果你的指挥控制系统有一半是a怎么办?那么你就不能压缩它了。把所有的文件都拉到一个文件里就可以了。在这种情况下,不需要考虑30Mb。根据我的数据,这种情况很少发生。