分割的数据帧使用python取决于csv文件大小

问题描述 投票:3回答:1

我有一个非常大的数据帧,有超过一百万条记录,5列。 我要救这个数据帧CSV和它拆分零件,使每一个文件,而压缩,最大500MB〜大小。是否有可能做到这一点不保存数据帧到我的机器,并检查它呢?

python pandas csv split
1个回答
2
投票

你可以不知道CSV文件的大小,但不保存。这是可能的救大数据帧的一部分,并使用它的文件大小每行估计大小。

import pandas as pd

big_df = pd.DataFrame(data=pd.np.random.randn(int(2e6), 5))

big_df.iloc[:100000].to_csv('temp.csv')

# look at temp.csv file size - 100 000 rows is 10 MB for me
# if I want about 50 MB per file I store to CSV a half million rows
# set it manually or you can compute it with os.path.getsize('temp.csv')
rows_max = int(5e5)

row_from = 0
row_to = rows_max
file_n = 1

while True:
    fn_i = 'big_%s.csv' % str(file_n).zfill(3)
    big_df.iloc[row_from:row_to].to_csv(fn_i)

    if row_to > big_df.index.size:
        break

    row_from = row_to
    row_to = row_from + rows_max
    file_n += 1
© www.soinside.com 2019 - 2024. All rights reserved.