[英]Trying to make a list array with txt data, Python
44.5000 70.5000 1.0000 44.0000 66.0000 1.0000 33.0000 76.5000 1.0000
我正在尝试使用 numpy 将这种数据变成这样的数组
''' ([[44.5000, 70.5000, 1.0000], [44.0000,66.0000,1.0000],[3.0000,76.5000,1.0000]]) '''
我试过这段代码,但这段代码要求我输入一个数据一百次
''' t_d = [list(map(float, input().split())) for _ in range(60)] '''
那么有没有办法将txt文件中的数据直接转成数组呢?
a = np.loadtxt(r'c:\test\nptext.txt')
print(a)
输出:
[[44.5 70.5 1. ]
[44. 66. 1. ]
[33. 76.5 1. ]]
import numpy as np
from io import StringIO
txt = """44.5000 70.5000 1.0000
44.0000 66.0000 1.0000
33.0000 76.5000 1.0000
"""
mfile = StringIO()
mfile.write(txt)
mfile.seek(0)
a = np.loadtxt(mfile)
print(a)
import numpy as np
from io import StringIO
import pyperclip
txt = pyperclip.paste()
mfile = StringIO()
mfile.write(txt)
mfile.seek(0)
a = np.loadtxt(mfile)
pyperclip.copy(a.__str__())
尝试这个:
with open("text.txt", "r") as file:
lines = file.readlines()
array = np.array([i.split() for i in lines], dtype="float")
print(array)
输出:
array([[44.5, 70.5, 1. ],
[44. , 66. , 1. ],
[33. , 76.5, 1. ]])
如果要将字符串转换为 Numpy 数组,可以使用np.fromstring
。
import numpy as np
string = "44.5000 70.5000 1.0000 44.0000 66.0000 1.0000 33.0000 76.5000 1.0000"
a = np.fromstring(string, sep=" ")
这给出了以下输出。
>>> a
array([44.5, 70.5, 1. , 44. , 66. , 1. , 33. , 76.5, 1. ])
然后,您可以使用np.reshape
将您的 Numpy 数组重塑为具有 3 列的二维数组。
>>> np.reshape(a, (-1, 3))
array([[44.5, 70.5, 1. ],
[44. , 66. , 1. ],
[33. , 76.5, 1. ]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.