[英]When converting a pandas dataframe to csv, how can i seperate the headers of the dataframe into different columns of the csv-file?
I am trying to scrape data from twitter by using the snscrape.我正在尝试使用 snscrape 从 twitter 中抓取数据。 After getting a list with 100 tweets, i am creating a dataframe with the tweets list by using pandas.
在获得包含 100 条推文的列表后,我正在使用 pandas 创建带有推文列表的 dataframe。 After converting the dataframe to a csv it looks like the following:
将 dataframe 转换为 csv 后,它如下所示:
https://i.stack.imgur.com/YRz0S.png https://i.stack.imgur.com/YRz0S.png
I would like to seperate the headers of the dataframe, so that one header of the dataframe defines one column in the csv-file.我想分离 dataframe 的标题,以便 dataframe 的一个 header 定义 csv 文件中的一列。 How can i do that?
我怎样才能做到这一点?
Here you can see my current code:在这里你可以看到我当前的代码:
import snscrape.modules.twitter as sntwitter
import pandas
# Creating list to append tweet data to
tweets_list2 = []
# Using TwitterSearchScraper to scrape data and append tweets to list
for i, tweet in enumerate(
sntwitter.TwitterSearchScraper('').get_items()):
if i > 100:
break
tweets_list2.append([tweet.date, tweet.id, tweet.content, tweet.user.username])
# Creating a dataframe from the tweets list above
tweets_df2 = pandas.DataFrame(tweets_list2, columns=['Datetime', 'Tweet Id', 'Text', 'Username'])
# converting the json string to a csv
export_csv = tweets_df2.to_csv (r'C:\Users\...\Desktop\Twitter2.csv', index = False)
By the way, I am a bloody beginner with python.顺便说一句,我是 python 的血腥初学者。 Thank you in advance!
先感谢您!
try this尝试这个
import pandas as pd
export_csv = pd.DataFrame({'Datetime,Tweet id,Text,Username': ['dfdnkdf,dfadfdsa,dfddfdfd,sdfdkjdfjjjjfd']})
export_csv = export_csv. iloc[:, 0].str.split(',', expand=True)
export_csv.columns =['Datetime', 'Tweet id', 'Text', 'Username']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.