将numpy.ndarray值从bytes转换为float

时间:2016-05-27 20:33:48

标签: python python-3.x numpy python-3.4

我使用numpy和Python 3.4从.csv文件中读取数据。

以下是CSV文件的示例:

"05/27/2016 09:45:37.816","187666432","7921470.8554087048","0","95.202655176457412","82.717061054954783","1.4626657999999999","158","5"
"05/27/2016 09:45:38.819","206884864","10692185.668858336","0","101.33018029563618","93.535551042125718","2.4649584999999998","158","5"

这是我的代码示例,用于从上面的CSV中提取数据:

import os
import numpy as np

path = os.path.abspath('sample.csv')
csv_contents = np.genfromtxt(path, dtype=None, delimiter=',', autostrip=True, skip_header=0,
                             usecols=(1, 2, 3, 4, 5, 6, 7, 8))

num_cols = csv_contents.shape[1]

for x in np.nditer(csv_contents):
    print('Original value: {0}'.format(x))
    print('Decoded value: {0}'.format(x.tostring().decode('utf-8')))
    val = x.tostring().decode('utf-8').replace('\x00', '').replace('"', '')
    print('Without hex and ": {0}'.format(val))

    try:
        print('Float value:\t{0}\n'.format(float(val)))
    except ValueError as e:
        raise e

示例输出:

Original value: b'"187666432"'
Decoded value: "187666432"���������
Without hex and ": 187666432
Float value:    187666432.0

Original value: b'"7921470.8554087048"'
Decoded value: "7921470.8554087048"
Without hex and ": 7921470.8554087048
Float value:    7921470.855408705

Original value: b'"0"'
Decoded value: "0"�����������������
Without hex and ": 0
Float value:    0.0

在我的for循环中,要将x值转换为浮点数,我必须这样做:

val = x.tostring().decode('utf-8').replace('\x00', '').replace('"', '')

这不是特别优雅,容易出错。

问题1: 有更好的方法吗?

问题2: 为什么x.tostring().decode('utf-8')在处理整数时会评估"158"���������������之类的内容?十六进制来自x.tostring()

1 个答案:

答案 0 :(得分:2)

回答第一个问题:

我强烈建议您使用pandas to read in csv files

In [11]: pd.read_csv(path, header=None)
Out[11]:
                         0          1             2  3           4          5         6    7  8
0  05/27/2016 09:45:37.816  187666432  7.921471e+06  0   95.202655  82.717061  1.462666  158  5
1  05/27/2016 09:45:38.819  206884864  1.069219e+07  0  101.330180  93.535551  2.464958  158  5

它“嗅出”你是否引用了字符串,一个不带引号的字符串,尽管这可以是明确的。

回答第二个问题:

如果使用flatten而不是nditer,则不会添加\x00 s(使每个字符串的长度为20; s20 dtype):

In [21]: a
Out[21]:
array([[b'"187666432"', b'"7921470.8554087048"', b'"0"',
        b'"95.202655176457412"', b'"82.717061054954783"',
        b'"1.4626657999999999"', b'"158"', b'"5"'],
       [b'"206884864"', b'"10692185.668858336"', b'"0"',
        b'"101.33018029563618"', b'"93.535551042125718"',
        b'"2.4649584999999998"', b'"158"', b'"5"']],
      dtype='|S20')

In [22]: [i.tostring() for i in np.nditer(a)]
Out[22]:
[b'"187666432"\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"7921470.8554087048"',
 b'"0"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"95.202655176457412"',
 b'"82.717061054954783"',
 b'"1.4626657999999999"',
 b'"158"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"5"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"206884864"\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"10692185.668858336"',
 b'"0"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"101.33018029563618"',
 b'"93.535551042125718"',
 b'"2.4649584999999998"',
 b'"158"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',
 b'"5"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00']

In [23]: [i.tostring() for i in a.flatten()]
Out[23]:
[b'"187666432"',
 b'"7921470.8554087048"',
 b'"0"',
 b'"95.202655176457412"',
 b'"82.717061054954783"',
 b'"1.4626657999999999"',
 b'"158"',
 b'"5"',
 b'"206884864"',
 b'"10692185.668858336"',
 b'"0"',
 b'"101.33018029563618"',
 b'"93.535551042125718"',
 b'"2.4649584999999998"',
 b'"158"',
 b'"5"']
相关问题