在pandas中将int32强制为dtype,而不是int64加载带有dtype和转换器的ucsv

2024-05-23 21:33:42 发布

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

https://github.com/pandas-dev/pandas/pull/2708表示其他类型的传播正在工作,但是,我无法将十六进制编码的值加载到int32中,它们作为int64进入数据帧

数据

2009-01-01T18:55:25Z,574,575,574,575,574,575,574,575,2,True
2009-01-01T18:56:55Z,574,575,574,575,573,574,573,574,2,True
2009-01-01T18:57:25Z,573,574,573,574,573,574,573,574,2,True
2009-01-01T18:57:30Z,573,574,573,574,573,574,573,574,2,True
2009-01-01T19:07:20Z,574,575,574,575,574,575,574,575,1,True
2009-01-01T19:07:55Z,574,575,574,575,574,575,574,575,1,True

姓名:

^{pr2}$

转换函数:

def hex2int(x):
    return int(x, 16) * 100

转换器:

convs = { i : hex2int for i in range(1,9) }

数据类型:

raw_dtypes = {
    'datetime': datetime.datetime,
    'sensorA': 'int32',
    'sensorA': 'int32',
    'sensorA': 'int32',
     ...
    'signal': 'int32',
}

读取csv:

df = pd.read_csv(filepath, delimiter=',', header=None, names=names, dtype=raw_dtypes, usecols=range(0, NUM_COLS-1), converters=convs, parse_dates=['datetime'])

结果:

>>> df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1308 entries, 0 to 1307
Data columns (total 10 columns):
datetime    1308 non-null datetime64[ns]
sensorA     1308 non-null int64
sensorB     1308 non-null int64
sensorC     1308 non-null int64
sensorD     1308 non-null int64
sensorE     1308 non-null int64
sensorF      1308 non-null int64
sensorG    1308 non-null int64
sensorH    1308 non-null int64
signal      1308 non-null int32
dtypes: datetime64[ns](1), int32(1), int64(8)

最后一列('signal')不使用转换器,而是根据文档使用正确的数据类型:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html如果指定了转换器,则应用它们而不是数据类型转换。

我很确定我不会把任何东西溢到int64,我的范围是160000-80000。我试着把转换器的返回转换为 return np.int32(x, 16) * 100但这并没有改变任何东西


Tags: csv数据truepandasdatetimesignalreturnnull
1条回答
网友
1楼 · 发布于 2024-05-23 21:33:42

如文档所述,如果为列同时指定了converter和{},则只应用converter。我认为在版本0.20+中,这会生成一个警告。在

如果应用了converter,则该列中的数据将采用通用推理路径,就像传递了pd.Series([...converted data ...],该路径使用int64作为默认值。在

所以现在,您所能做的最好的就是在事实发生之后对dtype进行强制转换。比如:

df = df.astype({'sensorA': 'int32', 'sensorB': 'int32'}) #etc

相关问题 更多 >