2017-04-11 90 views
0

我有一个脚本,它搜索Twitter中的某个术语,然后输出一些返回结果的属性。尝试向numpy数组添加内容

我想只是一个空白数组返回。任何想法为什么?

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的:)

+0

坚持列表附加在循环中。它更快,更容易。 – hpaulj

回答

0

np.append不修改数组,你需要分配结果回:

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

检查help(np.append)

注意 append做不在原地发生:分配新阵列并填充 。

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

0

下面是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) 

但随着许多项目

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

应该工作一样好concatenate作品;更好,因为列表追加更快。或删除嵌套的水平,让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个输入。等等。