简体   繁体   中英

How to create a numpy array from a txt file

I import a txt file with

np.genfromtxt(file_name, dtype='str')

I could for example get the following numpy array

['aaa' 'aaa' 'a']

What i would like to end up with is a numpy array looking like this

[['a', 'a', 'a'], ['a', 'a', 'a'], ['a', 'a', 'a']]

Take in mind, that the text file has only 1 a in the last row, so the script should automatically add another 2 a's to match the longest list in the array.

i've managed to make commas between the 3 strings with

[s.replace(' ', ',') for s in file]

But this doesn't seem to work if i would replace the space with ][.

any suggestions?

Are you looking for something like

str = "'aaa' 'aaa' 'a'"
str2 = str.replace("'a'","'a' 'a' 'a'")
str3 = str2.replace("'aaa' ","'a' 'a' 'a',")
str4 = str3.replace("'aaa'","'a' 'a' 'a',")
my_data2 = [str4.split(',') for x in str4.split('|')]
print(my_data2)

NOTE: Sorry for my basic reply, it's my very first answer. Hope that helped.

EDIT

[s.replace("'a'","'a','a','a'") for s in file] # add 3 'a's at the last one
[s.replace("'aaa' ","'a','a','a' ") for s in file] # split each one of the 3 'aaa's in the first to items
[s.split(" ") for s in file] # create 3 item "'a', 'a', 'a'" list per line
def func(file_name):
  arr = np.genfromtxt(file_name, dtype='str')
  # this line is in case you omitted the ',' between strings in loaded numpy array from your question
  # arr = arr.tolist().split() 
  l = []
  for i in arr:
    el = list(i)
    while len(el) < 3:
      el.append('a')
    l.append(el)
return np.array(l)

I hope this is ok for you.

Usig a list comprehension.

Ex:

import numpy as np

data = np.genfromtxt(filename, dtype='str')
mValue = len(max(data, key=lambda x: len(x)))
print([[j for j in i.ljust(mValue, i[0])] for i in data])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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