pandas 熊猫系列到 Excel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23365466/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:59:08  来源:igfitidea点击:

Pandas Series to Excel

pythonpandas

提问by ojdo

The pandas.Series object does have many to_*functions, yet it lacks a to_excelfunction. Is there an easier/better way to accomplish the export in line 3 of this snippet? It feels clunky to first convert the Series to a DataFrame simply for a simple I/O:

pandas.Series 对象确实有很多to_*功能,但它缺少一个to_excel功能。是否有更简单/更好的方法来完成此代码段第 3 行中的导出?首先将 Series 转换为 DataFrame 只是为了一个简单的 I/O,感觉很笨拙:

import numpy as np
import pandas as pd
s = pd.Series([1,3,5,np.nan,6,8])
pd.DataFrame(s).to_excel('s.xlsx', 's')

回答by Phillip Cloud

You can either:

您可以:

1. construct a DataFramefrom the start,

1.DataFrame从一开始就构造一个,

in which case you've already answered your own question.

在这种情况下,您已经回答了自己的问题。

2. Use Series.to_frame()

2. 使用 Series.to_frame()

s.to_frame(name='column_name').to_excel('xlfile.xlsx', sheet_name='s')

回答by ojdo

New in 0.20: Series.to_excel()

0.20 中的新功能:Series.to_excel()

Beginning with pandas version 0.20, Series now supports to_exceldirectly (see PR #8825for details):

从 pandas 0.20 版本开始,Series 现在to_excel直接支持(详见PR #8825):

import pandas as pd
s = pd.Series([0, 1, 2, 4, 8, 16], name='a_series')
s.to_excel('foo.xlsx')

Contents of file foo.xlsx:

文件 foo.xlsx 的内容:

  |  A | B         | 
--+----+-----------+---------------------
1 |    | a_series  | 
2 |  0 | 0         | 
3 |  1 | 1         | 
4 |  2 | 2         | 
5 |  3 | 4         | 
6 |  4 | 8         | 
7 |  5 | 16        | 
-.           ,---------------------------
  \ Sheet 1 /  \ Sheet 2 / \ Sheet 3 /