Creating a 2D array from a one line txt file in Python - python

I'm attempting to read a one line text file into an array in python, but I am struggling with actually getting the file to transform into an 2D array. This is the text file:
6 4 0 0 1 0 0 0 2 0 1 0 1 1 0 0 1 0 0 0 0 0 0 0 3 0
The first number (6) represents the columns and the second number (4) represents the rows. Here is the code I have so far:
maze_1d_arr = open(sys.argv[1], 'r')
maze = []
maze_split = np.array([maze_1d_arr])
size_X = len(maze_split)
size_Y = len(maze_split[0])
maze_grid = [int(x) for x in maze_split[2:]]
maze = np.array(maze_grid).reshape(size_X, size_Y)
start = np.where(maze_split == 2)
end = np.where(maze_split == 3)
path = astar(maze, start, end)
print(path)
Sorry if this question has been asked before but I'm stumped at how to get it to work. Any help would be appreciated!

import numpy as np
x = np.array([6, 4, 0, 0, 1, 0, 0, 0, 2, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 3, 0])
print(x[2:].reshape(x[[1,0]]))
[[0 0 1 0 0 0]
[2 0 1 0 1 1]
[0 0 1 0 0 0]
[0 0 0 0 3 0]]

Related

how to create an array of (100,19) size with each row as a vector of 19 values [0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0] in python?

I need to create an array of size (100,19) in python where each row is a fixed 19 valued vector of value [0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0]?
Any solution suggested?
a = np.zeros((100,19))
a[:,11] = 1
a = [0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
b = np.array(a)
c = np.tile(a,(100,1))
c.shape
Output:
(100, 19)
You can do it with np.zeros
array0 = np.zeros((100,19))
array0[:,11] = 1
On the other hand, if you want to have all one element
array1 = np.ones((100,19))
array1[:,11] = 0
np.full is a useful function for this purpose:
a = [0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
result=np.full((100,19),a )
result.shape
output:
(100,19)

how to move specific part of a 2d array to either left right up or down?

I know that you can move an array with NumPy so if you use np.roll you can shift array to right or to the left. I was wondering how to move a specific set of values with in the array to either left right up or down.
for example
if I wanted to move what is circled in red to the left how would i be able to move that and nothing else?
numpy can use slice to get subarray and later assing it in different place
import numpy as np
x = [
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ],
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ]
]
arr = np.array(x)
print(arr)
subarr = arr[0:2,1:4] # get values
print(subarr)
arr[0:2,0:3] = subarr # put in new place
print(arr)
Result:
[[0 1 2 1 0 0 1 2 1 0]
[0 1 2 1 0 0 1 2 1 0]]
[[1 2 1]
[1 2 1]]
[[1 2 1 1 0 0 1 2 1 0]
[1 2 1 1 0 0 1 2 1 0]]
It keeps original values in [0][1], [1][1]. If you want remove them then you could copy subarray, set zero in original place, and put copy in new place
import numpy as np
x = [
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ],
[0, 1, 2, 1, 0, 0, 1, 2, 1, 0 ]
]
arr = np.array(x)
print(arr)
subarr = arr[0:2,1:4].copy() # duplicate values
print(subarr)
arr[0:2,1:4] = 0 # remove original values
arr[0:2,0:3] = subarr # put in new place
print(arr)
Result
[[0 1 2 1 0 0 1 2 1 0]
[0 1 2 1 0 0 1 2 1 0]]
[[1 2 1]
[1 2 1]]
[[1 2 1 0 0 0 1 2 1 0]
[1 2 1 0 0 0 1 2 1 0]]

Python: updating a single item in a list, updates the entire list [duplicate]

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 3 years ago.
I have a piece of code that should be updating a single item in a list but instead updates the entire list.
Here is the code
a = [
[(0, 0), (3, 4)]
]
board = [[0] * 5] * 5
for solution in a:
for _x, _y in solution:
board[_x][_y] = 1
print(board)
Expected output:
1 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 1
0 0 0 0 0
Actual output:
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
1 0 0 0 1
Your problem resides in this line:
board = [[0] * 5] * 5
[[0] * 5] * 5 replicates the resulting list of [0, 0, 0, 0, 0] five times so that the reference remains the same across the board:
print([id(i) for i in board])
[59200896, 59200896, 59200896, 59200896, 59200896]
This makes it impossible to make the change individually.
Instead, do this:
board = [[0] * 5 for _ in range(5)]
print([id(i) for i in board])
[45118008, 45045120, 43900680, 43899760, 45119088]
The list comprehension will create a distinct object reference for each inner list, and the objects can now be updated individually:
[
[1, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]
]
try the below code
a = [
[(0, 0), (3, 4)]
]
board = [x[:] for x in [[0] * 5] * 5]
for solution in a:
for _x, _y in solution:
board[_x][_y] = 1
print(board)

Reading 2d array from file in Python

The following code fills a 2d array (grid) with random numbers(0 or 1):
def create_initial_grid(rows, cols):
grid = []
for row in range(rows):
grid_rows = []
for col in range(cols):
if random.randint(0, 7) == 0:
grid_rows += [1]
else:
grid_rows += [0]
grid += [grid_rows]
return grid
I want to fill the grid from a text file that looks like this:
7
0,0,0,0,0,0,0
0,0,1,0,1,0,0
0,0,1,1,1,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
0,0,0,0,0,0,0
Other option is to use numpy.loadtxt to read .txt (since you are use the array and matrix format):
data = np.loadtxt("text.txt", delimiter=",",dtype=int , skiprows=1)
print(data)
Out:
[[0 0 0 0 0 0 0]
[0 0 1 0 1 0 0]
[0 0 1 1 1 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]]
Note:
skiprows=1 # parameter for skipping the first line when reading from
the file.
dtype=int parameter for reading in the int format (default is
float)
You can read the file, with:
with open('myfile.txt') as f:
next(f) # skip the first line
data = [list(map(int, line.strip().split(','))) for line in f]
Here next(..) will move the cursor to the next line, since the first here contains a 7.
If there is data after the lines, we might want to prevent reading that, and use:
from itertools import islice
with open('myfile.txt') as f:
n = int(next(f)) # skip the first line
data = [list(map(int, line.strip().split(','))) for line in islice(f, n)]
For both file fragments here, the result is:
>>> data
[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]
filesname = "t.txt"
with open(filesname) as f:
lines = f.read().split()
n = lines[0]
data_lines = lines[1:]
data = [map(int, row.split(",")) for row in data_lines]
print(data)
Hope this helps!

how to skip the first line of a file in python

I need to write a code to read a .txt file, which is a matrix displayed as below, and turn it into an new integer list matrix. However, I want to skip first line of this .txt file without manually deleting the file. I do not know how to do that.
I have written some code. It is able to display the matrix, but I am unable to get rid of the first line:
def display_matrix(a_matrix):
for row in a_matrix:
print(row)
return a_matrix
def numerical_form_of(a_list):
return [int(a_list[i]) for i in range(len(a_list))]
def get_scoring_matrix():
scoring_file = open("Scoring Matrix")
row_num = 0
while row_num <= NUMBER_OF_FRAGMENTS:
content_of_line = scoring_file.readline()
content_list = content_of_line.split(' ')
numerical_form = numerical_form_of(content_list[1:])
scoring_matrix = []
scoring_matrix.append(numerical_form)
row_num += 1
#print(scoring_matrix)
display_matrix(scoring_matrix)
# (Complement): row_num = NUMBER_OF_FRAGMENTS
return scoring_matrix
get_scoring_matrix()
Scoring Matrix is a .txt file:
1 2 3 4 5 6 7
1 0 1 1 1 1 1 1
2 0 0 1 1 1 1 1
3 0 0 0 1 1 1 1
4 0 0 0 0 1 1 1
5 0 0 0 0 0 1 1
6 0 0 0 0 0 0 1
7 0 0 0 0 0 0 0
The result of my code:
[1, 2, 3, 4, 5, 6, 7]
[0, 1, 1, 1, 1, 1, 1]
[0, 0, 1, 1, 1, 1, 1]
[0, 0, 0, 1, 1, 1, 1]
[0, 0, 0, 0, 1, 1, 1]
[0, 0, 0, 0, 0, 1, 1]
[0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 0]
just put a scoring_file.readline() before the while loop.
I suggest using an automated tool:
import pandas
df = pandas.read_table("Scoring Matrix", delim_whitespace = True)
If you insist doing it yourself, change the while loop;
while row_num <= NUMBER_OF_FRAGMENTS:
content_of_line = scoring_file.readline()
if row_num == 0:
content_of_line = scoring_file.readline()

Categories