2 回答
TA贡献1735条经验 获得超5个赞
以下代码创建了一个新的数据框(表),其中包含每方参议员的推文
# 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)
输出应该是这样的
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条经验 获得超5个赞
我想你快到了。如果你想保持循环,而不是打印,你可以将该数据加载到数据帧中。首先定义一个新的数据框
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"]
添加回答
举报