pandas 将 DataFrame 列写入文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14412181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Writing DataFrame column to a file
提问by Aris Epan
Use the dframe from pandas module:
使用 pandas 模块中的 dframe:
df = dframe.resample('t', how = 'sum')
And after that I want to write the data in a new file. I use this:
之后我想将数据写入一个新文件中。我用这个:
with open('dframe.txt', 'w') as fout:
fout.write(df.price1) #it is the first column
But it doesn't work.
但它不起作用。
回答by root
df.price1returns a Series. Luckily Seriesalso has a to_csvmethod similar to the DataFrame's:
df.price1返回一个Series. 幸运的是Series还有一个to_csv类似于的方法DataFrame's:
Definition: Series.to_csv(self, path, index=True, sep=',', na_rep='',
float_format=None, header=False, index_label=None, mode='w', nanRep=None,
encoding=None)
Example usage:
用法示例:
df.price1.to_csv('outfile.csv')
回答by Rachel Gallen
try
尝试
df.to_csv('mydf.txt', sep='\t')
回答by Lynx-Lab
FYI there is also:
仅供参考,还有:
- DataFrame.to_html()
- DataFrame.to_excel()
- DataFrame.to_latex()
- and many others but not for file serialisation
- DataFrame.to_html()
- DataFrame.to_excel()
- DataFrame.to_latex()
- 和许多其他但不用于文件序列化
Only needed to use to_excel: the usage is in the method documentation or on http://pandas.pydata.org/pandas-docs/stable/
只需要使用 to_excel:用法在方法文档或http://pandas.pydata.org/pandas-docs/stable/
回答by Celso Fran?a
Did you try to use .values?
你试过用.values吗?
with open('dframe.txt', 'w') as fout:
fout.write(df.price1.values)
It returns a list containing all column values.
它返回一个包含所有列值的列表。

