使用“从Pandas读取csv”时,为特定列设置数据类型

2024-05-23 14:45:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很大的csv文件(~10GB),大约有4000列。我知道我期望的大多数数据是int8,因此我设置:

pandas.read_csv('file.dat', sep=',', engine='c', header=None, 
                na_filter=False, dtype=np.int8, low_memory=False)

问题是,最后一列(第4000位)是int32,我是否可以告诉read_csv默认使用int8,在第4000列,使用int32

多谢各位


Tags: 文件csv数据nonefalsepandasreadengine
2条回答

由于没有标题,列名是它们出现的整数顺序,即第一列是df[0]。要以编程方式将最后一列设置为int32,您可以读取文件的第一行以获取数据帧的宽度,然后构建一个整数类型字典,使用列数作为键

import numpy as np
import pandas as pd

with open('file.dat') as fp:
    width = len(fp.readline().strip().split(','))
    dtypes = {i: np.int8 for i in range(width)}
    # update the last column's dtype
    dtypes[width-1] = np.int32

    # reset the read position of the file pointer
    fp.seek(0)
    df = pd.read_csv(fp, sep=',', engine='c', header=None, 
                     na_filter=False, dtype=dtypes, low_memory=False)

如果您确定了数字,您可以像这样重新创建字典:

dtype = dict(zip(range(4000),['int8' for _ in range(3999)] + ['int32']))

考虑到这是可行的:

import pandas as pd
import numpy as np
​
data = '''\
1,2,3
4,5,6'''
​
fileobj = pd.compat.StringIO(data)
df = pd.read_csv(fileobj, dtype={0:'int8',1:'int8',2:'int32'}, header=None)
​
print(df.dtypes)

返回:

0     int8
1     int8
2    int32
dtype: object

从文档中:

dtype : Type name or dict of column -> type, default None

Data type for data or columns. E.g. {‘a’: np.float64, ‘b’: np.int32} Use str or object to preserve and not interpret dtype. If converters are specified, they will be applied INSTEAD of dtype conversion.

相关问题 更多 >