我有一个很大的 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 列,使用 int 32 吗?
谢谢
最佳答案
如果您确定数字,您可以像这样重新创建字典:
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.
关于python - 使用 pandas 中的 read_csv 时为特定列设置数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50642777/