我建议在导入之前通过导入一行来构建 dtype 变量,以便您对默认类型进行默认 dict 理解,然后将列修改为特殊类型。我引入 StringIO 只是为了运行下面的测试用例。
import pandas as pd
import numpy as np
from io import StringIO
dummyCSV = """header 1,header 2,header 3
1,2,3
4,5,6
7,8,9
11,12,13
14,15,16"""
blabblab_csv = StringIO(dummyCSV, newline='\n')
limitedRead = pd.read_csv(blabblab_csv, sep=",", nrows = 1)
#set a default type and populate all column types
defaultType = np.float64
dTypes = {key: defaultType for key in list(limitedRead.columns)}
#then override the columns you want, using the integer position
dTypes[limitedRead.columns[1]] = np.int32
blabblab_csv = StringIO(dummyCSV, newline='\n') #reset virtual file
fullRead = pd.read_csv(blabblab_csv, sep=",", dtype = dTypes)
我知道这对你来说可能有点晚了,但我只需要为我正在从事的一个项目这样做,所以希望下一次搜索该主题的人会有一个答案等待他们。