繁体   English   中英

试图用txt数据制作一个列表数组,Python

[英]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. ]]

Edit2(内存文件)

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)

Edit3(剪贴板输入和输出)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM