2017-04-11 7 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

가 여기에 귀하의 경우 arrnp.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) 

의 소스 코드 것은 모양 (0,3)부터 시작 배열입니다. values은 3 요소 목록입니다. 전화 번호는 concatenate입니다.

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

그러나

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

그냥 잘 작동해야 많은 항목 concatenate 작동합니다 : 그래서 append 호출은 그냥 목록 추가가 빠르기 때문에 더 좋습니다. 아니면이 np.array([[1,2,3],[4,5,6],[7,8,9]])으로 수행하는 것처럼, 중첩의 수준을 제거하고 np.array 새로운 축에 그들을 쌓아 보자

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

np.append 여러 문제가있다. 틀린 이름. 장소에서 행동하지 않습니다. Hides concatenate. 많은 경고없이 평평하게합니다. 한 번에 2 개의 입력으로 제한합니다.