首页 > 解决方案 > 从文件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'

标签: python-3.x

解决方案


试试下面的代码,希望对你有帮助:

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)

希望这可以帮助 :)


推荐阅读