首页 > 解决方案 > 使用 genfromtxt 获取数据时遇到问题

问题描述

我有以下代码:

import pandas as pd
data = [['Initial height', param[4]],
        ['Exponential decay constant', param[1]],
        ['Angular frequency', param[2]],
        ['Phi offset', param[3]],
        ['The amplitude', param[0]]]
df = pd.DataFrame(data, columns=['Variable', 'Value'])
print(df)

writePath = '/Users/harryhat/Desktop/Droplet Experiment/Variables/Trial/water-3 variables.txt'
with open(writePath, 'w') as f:
    f.write(
        df.to_string(header = False, index = False)
    )

data = np.genfromtxt(writePath, usecols=2)

我想从中获取第二列并将其保存为数据。但是,当我尝试使用它时,第二个参数出现为 nan 但我不知道为什么。附件是显示它是什么类型以及它的值的控制台。有谁知道为什么我会为这个价值得到 nan ?任何帮助表示赞赏。

在此处输入图像描述

在此处输入图像描述

标签: pythonpandasnumpynumpy-ndarray

解决方案


用你写的:

    In [31]: with open('tst1.csv', 'w') as f:
    ...:     f.write(
    ...:         df.to_string(header = False, index = False)
    ...:     )
    ...: 


In [33]: cat tst1.csv
             Initial height  0.601793
 Exponential decay constant  0.612753
          Angular frequency  0.109519
                 Phi offset  0.301704
              The amplitude  0.649477

In [34]: np.genfromtxt('tst1.csv', usecols=2)
Out[34]: array([0.601793,      nan, 0.109519, 0.301704, 0.649477])

默认分隔符是空格。问题行有 4 个字段:

In [35]: np.genfromtxt('tst1.csv')
Traceback (most recent call last):
  File "<ipython-input-35-307e4ac22394>", line 1, in <module>
    np.genfromtxt('tst1.csv')
  File "/usr/local/lib/python3.8/dist-packages/numpy/lib/npyio.py", line 2080, in genfromtxt
    raise ValueError(errmsg)
ValueError: Some errors were detected !
    Line #2 (got 4 columns instead of 3)

如果相反我使用

In [37]: df.to_csv('tst.csv')

In [38]: cat tst.csv
,Variable,Value
0,Initial height,0.6017927371181283
1,Exponential decay constant,0.6127532376900192
2,Angular frequency,0.109519476902042
3,Phi offset,0.3017037244796229
4,The amplitude,0.6494771015260451

这可以很好地加载 col 2 - 初始nan是标题,我可以跳过:

In [39]: np.genfromtxt('tst.csv',delimiter=',', usecols=2)
Out[39]: 
array([       nan, 0.60179274, 0.61275324, 0.10951948, 0.30170372,
       0.6494771 ])

genfromtxt有很多参数,虽然没有to_csv.


推荐阅读