python-3.x - 从文件sring加载并在python中浮动
问题描述
我有数据:
A 5.6
F 4.2
D 45.5
A 8.45
我尝试了这三个代码,其中 file 是上面的数据文件,而 xfile 和 yfile 只是其中一个列。
import matplotlib.pyplot as plt
import numpy as np
x = np.genfromtxt('xfile',dtype='str')
y = np.loadtxt('yfile', unpack=True, usecols=[0])
print(x)
print(y)
import matplotlib.pyplot as plt
import numpy as np
with open('xfile', 'r') as file:
x = file.read().replace('\n', '')
y = np.loadtxt('yfile', unpack=True, usecols=[0])
print(x)
print(y)
import matplotlib.pyplot as plt
import numpy as np
with open('file', 'r') as file:
x = file.read().replace('\n', '')
y = np.loadtxt('file', unpack=True, usecols=[1])
print(x)
print(y)
在第三个脚本中有一个问题,我不知道如何只加载第一列。在第一个和第二个代码中,数据类型存在问题。
错误:
return float(x)
ValueError: could not convert string to float: b'CA'
解决方案
试试下面的代码,希望对你有帮助:
import matplotlib.pyplot as plt
import numpy as np
x = np.genfromtxt('xfile.txt',dtype='str')
y = np.loadtxt('yfile.txt', unpack=True, usecols=[0])
print(x)
print(y)
import matplotlib.pyplot as plt
import numpy as np
with open('xfile.txt', 'r') as file:
x = file.read().replace('\n', '')
y = np.loadtxt('yfile.txt', unpack=True, usecols=[0])
print(x)
print(y)
import matplotlib.pyplot as plt
import numpy as np
with open('xfile.txt', 'r') as file:
x = file.read().replace('\n', '')
y = np.loadtxt('yfile.txt', unpack=True)
print(x)
print(y)
希望这可以帮助 :)
推荐阅读
- php - 如何使用 PHP 在 Firebase 中自动导入存储桶 - Google Cloud Storage
- javascript - React - 解析错误:意外的令牌,预期的“;”
- mysql - 当应用于 MySQL 表列中的变量时,+0E0 究竟做了什么?
- pandas - 计算不同年份的每日平均值(日期时间)
- django - Celery/systemd 不与我的 django 应用程序对话
- java - 如何将opentrace拦截器添加到restTemplate?
- reactjs - 使用 React 在按键上播放声音
- python - If else 具有多个条件的函数-Python
- java - 如何将 Mapstruct 与 Ad Hoc Setter 一起使用
- sql - 使用一张表过滤另一张表而不连接