【问题标题】:how do I append an array in python?如何在 python 中追加一个数组?
【发布时间】:2021-09-22 16:19:20
【问题描述】:

我有一些不同大小的数组(例如 (140,9)、(120,9)、...、(123,9))。我需要将它们全部合并到一个数组中。我使用了以下代码,但它说 NumPy 数组没有 append 属性。你能告诉我该怎么做吗?

os.chdir("E:/pythoncode/feature") #change directory to downloads folder
files_path = [os.path.abspath(x) for x in os.listdir()]
fnames_transfer = [x for x in files_path if x.endswith(".npy")]
feature=np.zeros((2000,9))
for i in range(len(fnames_transfer)):
    data=np.load(fnames_transfer[i])
    feature.append(feature,data)

错误是:

Traceback (most recent call last):

  File "<ipython-input-7-98bd45171da9>", line 3, in <module>
    feature.append(feature,data)

AttributeError: 'numpy.ndarray' object has no attribute 'append'

【问题讨论】:

标签: python python-3.x numpy


【解决方案1】:

希望这会有所帮助!也添加了评论。

os.chdir("E:/pythoncode/feature") #change directory to downloads folder
files_path = [os.path.abspath(x) for x in os.listdir()]
fnames_transfer = [x for x in files_path if x.endswith(".npy")]
feature=np.zeros((2000,9))

feature_new = []#Added empty list to capture all the appended values
for i in range(len(fnames_transfer)):
    data=np.load(fnames_transfer[i])
    #feature.append(feature,data) ##instead of this use extend as the following 
    feature_new.extend([[feature,data]]) #changed the name from "feature" to "feature_new" to not to be confused with the other variable with a same name.
    #if .extend code line didnt work for you open the following line and remove the .extend
    #feature_new.append(feature,data)

【讨论】:

  • 当我从您的代码中删除功能时,它可以工作。例如 feature_new.extend([[data]])
  • 很有趣,这是好事还是坏事?您是否尝试过 .append (最后一行)?否则,如果一切正常,您可以接受代码。
  • 对于追加,我也只是使用了数据,feature_new.append(data)!
猜你喜欢
  • 2020-04-04
  • 2021-01-21
  • 1970-01-01
  • 2013-09-29
  • 2016-03-04
  • 2016-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多