[英]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.