【问题标题】:Numpy converts scientific notation to nan while reading CSVNumpy 在读取 CSV 时将科学记数法转换为 nan
【发布时间】:2019-02-25 00:50:57
【问题描述】:

我在使用 np.genfromtxt 读取 CSV 文件时遇到问题。 CSV 中的所有记录都是科学记数法,但是在使用 np.genfromtxt 读取文件时,数组中的每个项目都是“nan”。

CSV 中的示例行:1.02E+02;1.64E+00

In [1]: read = np.genfromtxt('13G-mapa-0001.CSV', delimiter=';')
In [2]: read
Out[2]:
array([[nan, nan],
   [nan, nan],
   [nan, nan],
   ...,
   [nan, nan],
   [nan, nan],
   [nan, nan]])

完整文件:

1,204619e+002;1,639486e+000 
1,214262e+002;1,623145e+000 
1,223904e+002;1,607553e+000 
1,233547e+002;1,592153e+000 
1,243189e+002;1,576472e+000 
1,252832e+002;1,560220e+000 
1,262474e+002;1,543355e+000 
1,272117e+002;1,526069e+000 
1,281759e+002;1,508706e+000 
1,291402e+002;1,491635e+000 
1,301044e+002;1,475144e+000 
1,310686e+002;1,459387e+000 
1,320329e+002;1,444416e+000

【问题讨论】:

  • 无法重现,使用仅包含示例行的 csv,它可以工作(返回:array([102. , 1.64])
  • 请您将文件添加到您的问题中。这将在未来对其他人有所帮助。

标签: python numpy scipy nan


【解决方案1】:

你的分隔符必须是逗号','而不是分号';'

编辑:问题是也有逗号,例如 1,25e+00 需要单独解析

def genfromtxt(file):
  from io import BytesIO
  with open(file, 'r') as f:
    lines = ' '.join([s.replace(',', '.') for s in f.readlines()])
  return np.genfromtxt(BytesIO(lines.encode('utf-8')), delimiter=';', dtype=np.float32)

这是我的解决方案

【讨论】:

  • 我认为这不是真的。 stackoverflow.com/questions/10140999/…
  • 是的,我刚刚注意到,这给我带来了另一个问题,有没有办法在 genfromtxt 完成的读数中将每个昏迷转换为一个点?
【解决方案2】:

基于this answer,您可以执行以下操作来转换逗号小数:

def conv(x):
    return x.replace(',', '.').encode()

read = np.genfromtxt((conv(x) for x in open("x.csv")), delimiter=';')

>>> read
array([[120.4619  ,   1.639486],
       [121.4262  ,   1.623145],
       [122.3904  ,   1.607553],
       [123.3547  ,   1.592153],
       [124.3189  ,   1.576472],
       [125.2832  ,   1.56022 ],
       [126.2474  ,   1.543355],
       [127.2117  ,   1.526069],
       [128.1759  ,   1.508706],
       [129.1402  ,   1.491635],
       [130.1044  ,   1.475144],
       [131.0686  ,   1.459387],
       [132.0329  ,   1.444416]])

【讨论】:

    【解决方案3】:

    pandas 提供了一种现代、快速且通用的方法:

    import pandas as pd
    table=pd.read_csv('data.csv',sep=';',decimal=',',header=None)
    arr=table.values
    

    array([[ 120.4619  ,    1.639486],
           [ 121.4262  ,    1.623145],
           [ 122.3904  ,    1.607553],
           [ 123.3547  ,    1.592153],
           [ 124.3189  ,    1.576472],
           [ 125.2832  ,    1.56022 ],
           [ 126.2474  ,    1.543355],
           [ 127.2117  ,    1.526069],
           [ 128.1759  ,    1.508706],
           [ 129.1402  ,    1.491635],
           [ 130.1044  ,    1.475144],
           [ 131.0686  ,    1.459387],
           [ 132.0329  ,    1.444416]])
    

    read_csv 提供比genfromtxt 更多的高级选项。

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      • 1970-01-01
      • 2023-02-17
      • 2017-07-30
      • 2015-07-03
      相关资源
      最近更新 更多