【问题标题】:Trying to append content to numpy array试图将内容附加到 numpy 数组
【发布时间】:2017-04-11 19:31:56
【问题描述】:

我有一个脚本,它在 Twitter 上搜索某个词,然后打印出返回结果的一些属性。

我正在尝试只返回一个空白数组。任何想法为什么?

public_tweets = api.search("Trump")

tweets_array = np.empty((0,3))

for tweet in public_tweets:

    userid = api.get_user(tweet.user.id)
    username = userid.screen_name
    location = tweet.user.location
    tweetText = tweet.text
    analysis = TextBlob(tweet.text)
    polarity = analysis.sentiment.polarity

    np.append(tweets_array, [[username, location, tweetText]], axis=0)

print(tweets_array)

我试图实现的行为类似于..

array = []
array.append([item1, item2, item3])
array.append([item4,item5, item6])

array 现在是[item1, item2, item3],[item4, item5, item6]

但是在 Numpy 中:)

【问题讨论】:

  • 坚持在循环中追加列表。它更快、更容易。

标签: arrays loops numpy tweepy textblob


【解决方案1】:

np.append 不修改数组,需要将结果赋值回去:

tweets_array = np.append(tweets_array, [[username, location, tweetText]], axis=0)

查看help(np.append):

请注意 append 不会就地发生:分配了一个新数组并且 填满。

在第二个示例中,您正在调用列表的append 方法,该方法发生在原地;这与np.append 不同。

【讨论】:

    【解决方案2】:

    这是np.append的源代码

    In [178]: np.source(np.append)
    In file: /usr/local/lib/python3.5/dist-packages/numpy/lib/function_base.py
    def append(arr, values, axis=None):
        ....docs
        arr = asanyarray(arr)
        if axis is None:
            .... special case, ravels
        return concatenate((arr, values), axis=axis)
    

    在您的情况下,arr 是一个数组,以形状 (0,3) 开头。 values 是一个 3 元素列表。这只是对concatenate 的一个电话。所以append 电话只是:

    np.concateante([tweets_array, [[username, location, tweetText]]], axis=0)
    

    但是concatenate 可以处理很多项目

    alist = []
    for ....:
       alist.append([[username, location, tweetText]])
    arr = np.concatenate(alist, axis=0)
    

    应该也能正常工作;更好,因为列表附加更快。或者删除一层嵌套,让np.array 将它们堆叠在一个新轴上,就像使用np.array([[1,2,3],[4,5,6],[7,8,9]]) 一样:

    alist = []
    for ....:
       alist.append([username, location, tweetText])
    arr = np.array(alist)   # or np.stack()
    

    np.append 有多个问题。名字错误。不就地行动。隐藏concatenate。在没有太多警告的情况下变平。一次将您限制为 2 个输入。等等

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-10
      • 2017-05-22
      • 2021-02-21
      • 2021-10-25
      • 2020-03-13
      • 2017-08-18
      相关资源
      最近更新 更多