gpt4 book ai didi

python - Pandas dataframe打印语句,格式化每行一行,无索引

转载 作者:太空宇宙 更新时间:2023-11-03 14:56:14 28 4
gpt4 key购买 nike

我有一个从 JSON 文件中提取的推文的 pandas 数据框:

# Grab the data from internet
with urllib.request.urlopen('http://some/url/tweets.json') as url:
data = json.loads(url.read().decode())

# Convert the data into a pandas data frame
df = pd.DataFrame(data)

# Select the pertinent information
df1 = df[['text','lang']]

# Print the individual tweets
tweets1 = tweets['text']

我现在想要打印一个 .txt 文件,每行包含每条推文。我尝试过:

with io.open("tweets.txt","w",encoding = 'utf8') as tweets:    
print(tweets1, file = tweets)

还有:

with io.open("tweets.txt","w",encoding = 'utf8') as tweets:    
print(tweets1.to_csv(header = False), file = tweets)

问题在于,在这两种情况下,各个推文都被分成多行。此外,csv 尝试包括行计数 - 这是我不想要的。我能做些什么?

最佳答案

我不确定是什么导致它在没有一些示例数据的情况下被分成多行。但是,您可以使用 join 将列表连接成字符串,并且如果您使用换行符作为分隔符,它应该按要求工作。

with open("tweets.txt", "w") as tweets: 
print('\n'.join(tweets1), file = tweets)

关于python - Pandas dataframe打印语句,格式化每行一行,无索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45551210/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com