2 回答

TA貢獻1735條經(jīng)驗 獲得超5個贊
以下代碼創(chuàng)建了一個新的數(shù)據(jù)框(表),其中包含每方參議員的推文
# Create an empty dataframe stub to append to later
all_tweets_df = pd.DataFrame(columns=['Senator', 'Party', 'Tweet'])
# Iterate over the initial dataframe
for _, row in full_senator_df.iterrows():
tweets = api.user_timeline(screen_name = row['Official Twitter'],
count = tweet_num,
include_rts = True)
senator_tweets_df = pd.DataFrame({'Senator': row['Senator'],
'Party': row['party'],
'Tweet': tweets})
# Append to the output
all_tweets_df = pd.concat([all_tweets_df, senator_tweets_df], sort=True)
輸出應(yīng)該是這樣的
Party Senator Tweet
0 Republican Shelby tweet1
1 Republican Shelby tweet2
2 Republican Shelby tweet3
0 Republican Murkowski tweet1
1 Republican Murkowski tweet2
2 Republican Murkowski tweet3
0 Republican Sullivan tweet1
1 Republican Sullivan tweet2
2 Republican Sullivan tweet3

TA貢獻1866條經(jīng)驗 獲得超5個贊
我想你快到了。如果你想保持循環(huán),而不是打印,你可以將該數(shù)據(jù)加載到數(shù)據(jù)幀中。首先定義一個新的數(shù)據(jù)框
dfTweets = pd.DataFrame() # place this before your while loop
row_num = 0
while ...
...
for status in tweets:
dfTweets.loc[0, row_num] = full_senator_df['Senator'][senator_count]
dfTweets.loc[1, row_num] = status.text,
dfTweets.loc[2, row_num] = full_senator_df['party'][senator_count]
row_num += 1
dfTweets.columns = ["Senator", "tweet_text"]
添加回答
舉報