1

I have some different number in here. It changes every time. I need to create a multidimensional array like
array[x][y] => x should include value by splitting before , and y should include ' ' empty.
How can i do that ? Thank you.

dat.xyz
2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9

output = open('dat.xyz', 'r') # See the r
output_list = output.read().strip().split(',')

I can find number before , but it shows in just one line. However, I want to do that multidimensional. It should split dimension to see empty ' '. Thank you.

Output should be following

[[2, 3, 4, 5, 6, 7, 8, 9], 
[2, 3, 4, 5, 6, 7, 8, 9], 
[2, 3, 4, 5, 6, 7, 8, 9], 
[2, 3, 4, 5, 6, 7, 8, 9]]
1
  • what is your expected output? Commented Sep 4, 2018 at 9:38

2 Answers 2

6

You should split first around spaces to get rows and then iterate on those rows to get the cells:

>>> rows = "2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9 2,3,4,5,6,7,8,9".split(' ')
>>> rows
['2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9', '2,3,4,5,6,7,8,9']
>>> [row.split(',') for row in rows]
[['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9'], ['2', '3', '4', '5', '6', '7', '8', '9']]

You could also convert those cells to integers:

>>> [[int(cell) for cell in row.split(',')] for row in rows]
[[2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9]]

or let numpy do the conversion for you:

>>> import numpy as np
>>> np.array([row.split(',') for row in rows], np.int)
array([[2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9]])
Sign up to request clarification or add additional context in comments.

1 Comment

Result is exactly what i want. But, what is row.split. Row is unknown here ? It gives some error. Also i read rows in my text file. Therefore just .split doesnot work. I should use something like that rows.read().strip().split(' '). Can you edit your code according to if i take it in a text file. Thank you.
1
import numpy as np

# read file and split over whitespace
with open('dat.xyz', 'r') as f:
    rows = f.read()
    rows = rows.split(' ')

arr = []

# split each value in row over comma, then convert each element to integer
for row in rows:
    row = row.split(',')
    for i in range(len(row)):
        row[i] = int(row[i])
    arr.append(row)

# convert to array
arr = np.array(arr)

arr

Output:

array([[2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9],
       [2, 3, 4, 5, 6, 7, 8, 9]])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.