尝试用 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. ]])
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. ]])