【问题标题】:csv to netCDF produces .nc files 4X larger than the original .csvcsv 到 netCDF 生成的 .nc 文件比原始 .csv 大 4 倍
【发布时间】:2018-08-09 18:10:37
【问题描述】:

我有许多大型 .csv 文件,我想使用 xrray 将它们转换为 .nc(即 netCDF 文件)。但是,我发现保存 .nc 文件需要很长时间,而且生成的 .nc 文件比原始 .csv 文件大得多(大 4 到 12 倍)。

下面是示例代码,展示了相同数据如何生成比保存在 .csv 中时大约 4 倍的 .nc 文件

import pandas as pd
import xarray as xr
import numpy as np
import os

# Create pandas DataFrame 
df = pd.DataFrame(np.random.randint(low=0, high=10, size=(100000,5)),
                   columns=['a', 'b', 'c', 'd', 'e'])

# Make 'e' a column of strings
df['e'] = df['e'].astype(str)

# Save to csv
df.to_csv('df.csv')

# Convert to an xarray's Dataset
ds = xr.Dataset.from_dataframe(df)

# Save NetCDF file
ds.to_netcdf('ds.nc')

# Compute stats
stats1 = os.stat('df.csv')
stats2 = os.stat('ds.nc')
print('csv=',str(stats1.st_size))
print('nc =',str(stats2.st_size))
print('nc/csv=',str(stats2.st_size/stats1.st_size))

结果:

>>> csv = 1688902 bytes
>>>  nc = 6432441 bytes
>>> nc/csv = 3.8086526038811015

如您所见,.nc 文件大约是 .csv 文件的 4 倍。

我发现this post 建议从类型“字符串”更改为类型“字符”会大大减少文件大小,但我如何在 xarray 中执行此操作?

另外,请注意,即使所有数据都是整数(即注释掉 df['e'] = df['e'].astype(str)),生成的 .nc 文件仍然比 .csv 大 50%

我是否缺少压缩设置? ...还是别的什么?

【问题讨论】:

    标签: python csv netcdf python-xarray netcdf4


    【解决方案1】:

    由于您仅使用从 0 到 9 的变量,因此在 CSV 文件中 1 个字节足以存储数据。 xarray,默认使用 int64(8 字节)作为整数。

    要告诉 xarray 使用 1 字节整数,你可以这样:

     ds.to_netcdf('ds2.nc',encoding = {'a':{'dtype': 'int8'},
          'b':{'dtype': 'int8'}, 'c':{'dtype': 'int8'}, 
          'd':{'dtype': 'int8'}, 'e':{'dtype': 'S1'}})
    

    生成的文件为 1307618 字节。压缩将进一步减少文件大小,尤其是对于非随机数据:-)

    【讨论】:

      【解决方案2】:

      我找到了自己问题的答案...

      1. 为每个变量启用压缩
      2. 对于列e,指定dtype 是“字符”(即S1

      在保存.nc文件之前,添加以下代码:

      encoding = {'a':{'zlib':True},
                  'b':{'zlib':True},
                  'c':{'zlib':True},
                  'd':{'zlib':True},
                  'e':{'zlib':True, 'dtype':'S1'}}
      ds.to_netcdf('ds.nc',format='NETCDF4',engine='netcdf4',encoding=encoding)
      

      新的结果是:

      >>> csv = 1688902 bytes
      >>>  nc = 1066182 bytes
      >>> nc/csv = 0.6312870729029867
      

      请注意,保存 .nc 文件仍然需要一些时间。

      【讨论】:

      • 值得注意的是,对于小型数据集,压缩可以使文件显着变大。
      猜你喜欢
      • 2021-06-21
      • 2022-07-29
      • 2021-04-12
      • 1970-01-01
      • 2021-05-25
      • 2021-02-04
      • 2015-05-19
      • 1970-01-01
      • 2016-08-04
      相关资源
      最近更新 更多