繁体   English   中英

如何从txt文件创建numpy数组

[英]How to create a numpy array from a txt file

我导入一个txt文件

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

我可以例如获取以下numpy数组

['aaa' 'aaa' 'a']

我想最终得到的是一个像这样的numpy数组

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

请记住,文本文件的最后一行只有1个a,因此脚本应自动添加另外2个a以匹配数组中最长的列表。

我设法使三个字符串之间的逗号

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

但这似乎不起作用,如果我将其替换为[]。

有什么建议么?

您是否正在寻找类似的东西

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)

注意:很抱歉,我的基本答复是我的第一个答案。 希望能有所帮助。

编辑

[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)

我希望这对您来说可以。

使用列表理解。

例如:

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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