[英]Format print statement pandas df
I have a pandas data frame like so: 我有一个像这样的熊猫数据框:
[in]print(lang_sorted)
[out]
frequency
lang
en 585
ar 179
es 147
ja 114
pt 113
und 109
tr 82
fr 43
ko 21
How can I print the data frame to a text file without any headers or spaces- so that the format is 'lang,freq'\\n where each line is a new line with no spaces or breaks in the file (and no ' ')? 如何将数据帧打印到没有任何标题或空格的文本文件中-以便格式为'lang,freq'\\ n,其中每一行都是换行,文件中没有空格或中断(并且也没有'') ?
I tried: print("{},{}".format(lang_sorted))
but this threw an error: IndexError: tuple index out of range
and also: print(lang_sorted.applymap("{0:.2f}".format))
but this just turned my frquencies to floats. 我尝试了:
print("{},{}".format(lang_sorted))
但这引发了一个错误: IndexError: tuple index out of range
,而且: print(lang_sorted.applymap("{0:.2f}".format))
但这只是使我的频率浮动。
The file I am printing this into is organized like such: 我将其打印到的文件是这样组织的:
# Create the twitter analytics text file
with io.open("twitter_analytics.txt","w",encoding='utf8') as twitter_analytics:
# Number of events
print(len(data))
# Number of tweets
print(len(tweets))
# Frequency of tweets by language
print("{},{}".format(lang_sorted))
twitter_analytics.close()
Use DataFrame.to_csv
. 使用
DataFrame.to_csv
。
df.to_csv('your-file.csv')
Or without headers: 或不带标题:
df.to_csv('your-file.csv', header=False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.