python - Numpy 在读取 CSV 时将科学计数法转换为 nan

标签 python numpy scipy nan

我在使用 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

最佳答案

分隔符必须是逗号“,”而不是分号“;”

编辑:问题是也有逗号,例如 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)

这是我的解决方案

关于python - Numpy 在读取 CSV 时将科学计数法转换为 nan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429696/

相关文章:

Python 字谜字符串

来自多个文件的 Python txt 矩阵

python - 协方差矩阵的对角元素不是 1 pandas/numpy

python - 使用嵌套 for 循环、条件和累加器的列表理解

python - 在numpy中获取结果数组的dtype

python - Zipf 分布 : How do I measure Zipf Distribution

python - 进程内存使用输出

python - 在 python 中从 excelsheet 中读取特定的单元格值

Python:转换小时分钟秒的行程持续时间并仅保留分钟数

python - 如何在 matplotlib 的树状图中添加颜色 - python 中的 scipy?