gpt4 book ai didi

python - 使用 pandas 中的 read_csv 时为特定列设置数据类型

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:31 24 4
gpt4 key购买 nike

我有一个很大的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com