【发布时间】:2020-11-22 00:39:07
【问题描述】:
我正在尝试读取 CSV 文件的内容,该文件包含我认为是 IEEE 754 单精度浮点数的十进制格式。
默认情况下,它们以 int64 格式读入。如果我用dtype = {'col1' : np.float32} 之类的东西指定数据类型,则dtype 会正确显示为float32,但它们与float 而不是int 的值相同,即。 1079762502 变为 1.079763e+09 而不是 3.435441493988037。
我已设法使用以下任一方法对单个值进行转换:
from struct import unpack
v = 1079762502
print(unpack('>f', v.to_bytes(4, byteorder="big")))
print(unpack('>f', bytes.fromhex(str(hex(v)).split('0x')[1])))
哪个产生
(3.435441493988037,)
(3.435441493988037,)
但是,我似乎无法使用 pandas 以矢量化方式实现这一点:
import pandas as pd
from struct import unpack
df = pd.read_csv('experiments/test.csv')
print(df.dtypes)
print(df)
df['col1'] = unpack('>f', df['col1'].to_bytes(4, byteorder="big"))
#df['col1'] = unpack('>f', bytes.fromhex(str(hex(df['col1'])).split('0x')[1]))
print(df)
抛出以下错误
col1 int64
dtype: object
col1
0 1079762502
1 1079345162
2 1078565306
3 1078738012
4 1078635652
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-8-c06d0986cc96> in <module>
7 print(df)
8
----> 9 df['col1'] = unpack('>f', df['col1'].to_bytes(4, byteorder="big"))
10 #df['col1'] = unpack('>f', bytes.fromhex(str(hex(df['col1'])).split('0x')[1]))
11
~/anaconda3/envs/test/lib/python3.7/site-packages/pandas/core/generic.py in __getattr__(self, name)
5177 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5178 return self[name]
-> 5179 return object.__getattribute__(self, name)
5180
5181 def __setattr__(self, name, value):
AttributeError: 'Series' object has no attribute 'to_bytes'
或者如果我尝试第二种方式,TypeError: 'Series' object cannot be interpreted as an integer
我在这里的 Python 知识有限,我想我可以遍历每一行,转换为十六进制,然后转换为字符串,然后剥离 0x,解压缩并存储。但这似乎非常复杂,在较小的样本数据集上已经花费了几秒钟,更不用说数十万个条目了。我在这里遗漏了一些简单的东西,有没有更好的方法?
【问题讨论】:
标签: python pandas numpy csv ieee-754