Arrays 尝试将内容附加到numpy数组
我有一个脚本,它在Twitter上搜索某个术语,然后为返回的结果打印出一些属性 我正在尝试返回一个空白数组。你知道为什么吗Arrays 尝试将内容附加到numpy数组,arrays,loops,numpy,tweepy,textblob,Arrays,Loops,Numpy,Tweepy,Textblob,我有一个脚本,它在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 =
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])
数组现在是[item1,item2,item3],[item4,item5,item6]
但是在Numpy:)中np.append
不会修改数组,您需要将结果分配回:
tweets_array = np.append(tweets_array, [[username, location, tweetText]], axis=0)
检查帮助(np.append)
:
注意
append
未在适当的位置发生:分配了一个新数组并
填满了
在第二个示例中,您正在调用list的append
方法,该方法发生在适当的位置;这不同于np.append
以下是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
是一个数组,从shape(0,3)
开始<代码>值
是一个3元素列表。只需调用连接
。所以append
调用就是:
np.concateante([tweets_array, [[username, location, tweetText]]], axis=0)
但是,串联
可以处理许多项
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])所做的那样:
np.append
有多个问题。名字错了。没有适当的行动。隐藏连接
。在没有太多警告的情况下变平。一次最多可输入2个输入。等等。坚持循环中的列表追加。它更快、更容易。
alist = []
for ....:
alist.append([username, location, tweetText])
arr = np.array(alist) # or np.stack()