如何从python中的文本文件创建数组

问题描述 投票:0回答:2

我的文本文件如下:

data.txt:

'[[[74,180],[74,215],[72,210],[72,210],.... [73,195]'

我有点困惑如何遍历目录中的文件,同时将它们放入2D数组中。到目前为止,我的代码是:

import nupym as np
f=open("data.txt","r",encoding="utf-8")
data=f.read()
array=np.array(data,dtype=np.int64)
print(array)

The output that I am seeking is array
[[ 74 180]
 [ 74 215]
 [ 72 210]
 ...
 [ 75 205]
 [ 75 190]
 [ 73 195]]
python-3.x
2个回答
0
投票
import pandas as pd

df=pd.read_csv('data.txt');
df.to_numpy();

此输出应为您提供numpy数组。在此处查看熊猫文档:https://pandas.pydata.org/pandas-docs/stable/reference/frame.html


0
投票

您显示的格式是JSON,如果没有引号,如果不缺少右括号,并且没有省略号。另外,numpy,而不是nupym。请确保问题中的信息正确。如果这些假设是正确的,则解决方案是:

import numpy as np
import json

with open("data.txt", "r", encoding="utf-8") as f:
    array = np.array(json.load(f))
© www.soinside.com 2019 - 2024. All rights reserved.