44.5000 70.5000 1.0000
44.0000 66.0000 1.0000
33.0000 76.5000 1.0000
I am trying to make this kind of data into an array like this using numpy
([[44.5000, 70.5000, 1.0000], [44.0000,66.0000,1.0000],[3.0000,76.5000,1.0000]])
I tried this code but this code requires me to input a data hundred times
t_d = [list(map(float, input().split())) for _ in range(60)]
so is there any way to make the data in txt file directly to array?
CodePudding user response:
Try this:
with open("text.txt", "r") as file:
lines = file.readlines()
array = np.array([i.split() for i in lines], dtype="float")
print(array)
Output:
array([[44.5, 70.5, 1. ],
[44. , 66. , 1. ],
[33. , 76.5, 1. ]])
CodePudding user response:
If you want to turn a string into a Numpy array, you can use 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=" ")
This gives the following output.
>>> a
array([44.5, 70.5, 1. , 44. , 66. , 1. , 33. , 76.5, 1. ])
Then, you can use np.reshape
to reshape your Numpy array into a 2D array with 3 columns.
>>> np.reshape(a, (-1, 3))
array([[44.5, 70.5, 1. ],
[44. , 66. , 1. ],
[33. , 76.5, 1. ]])
CodePudding user response:
a = np.loadtxt(r'c:\test\nptext.txt')
print(a)
Output:
[[44.5 70.5 1. ]
[44. 66. 1. ]
[33. 76.5 1. ]]
Edit2 (in-memory file)
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 (clipboard input & output)
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__())