python - 使用 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 ?任何帮助表示赞赏。
解决方案
用你写的:
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
.
推荐阅读
- c++ - 基于 C++ 模板的 get()
- google-cloud-platform - 在谷歌云托管上从试用到付款后,我的网站无法打开
- c# - 警告“字段 .... 从未分配给并且将始终具有其默认值 null”
- webpack - Webpack 5:如何允许 setImmediate?
- javascript - 算法的时间复杂度 - JavaScript
- php - 抽象工厂无法创建 magentoframeworkappdeploymentconfig 的实例(别名:Magento\Framework\App\DeploymentConfig)
- c++ - 如何按 shared_ptr 包含的索引比较两个向量索引
- r - 与 ifelse 语句一起应用,并且 is.na 不是“求和”而是输出矩阵 - 我的逻辑错误在哪里?
- android - 在 Android 4.2 上运行谷歌云语音 api
- c# - 使用 c# 替换字符串中的许多字符