【问题标题】:force int32 as dtype instead of int64 in pandas load_csv with dtype and converters在带有 dtype 和转换器的 pandas read_csv 中强制 int32 作为类型而不是 int64
【发布时间】:2017-10-12 03:28:04
【问题描述】:

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

名字:

names = [
    'datetime',
    'sensorA',
    'sensorB',
    'sensorC',
     ...
    'signal',
]

转换函数:

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',
}

read_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') 不使用转换器,并根据文档使用正确的 dtype:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html (如果指定了转换器,它们将被应用 INSTEAD 的 dtype 转换。 )

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

【问题讨论】:

  • 你能给我们一些数据吗?
  • @piRSquared 添加了一些数据

标签: python pandas numpy


【解决方案1】:

如文档所述,如果同时为列指定了 converterdtype,则只会应用 converter。我认为在版本 0.20+ 中会产生警告。

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

所以现在,您能做的最好的事情就是事后强制转换 dtype。比如:

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

【讨论】:

  • 那行得通,有机会我会提交功能请求或其他内容。有关改进日期时间处理的任何提示?喜欢指定索引吗?
  • @encore2097 在您的read_csv 通话中包含index_col=0, parse_dates=[0]。我无法让它发挥作用,并得出与克里斯布相同的结论。不要忘记接受这个答案并投赞成票:-)
猜你喜欢
  • 1970-01-01
  • 2019-10-06
  • 2022-08-04
  • 2022-08-18
  • 2020-03-01
  • 2018-04-23
  • 2016-11-02
  • 2021-01-02
  • 1970-01-01
相关资源
最近更新 更多