【问题标题】:Pandas Series to Excel熊猫系列到 Excel
【发布时间】:2014-06-15 10:31:24
【问题描述】:

pandas.Series 对象does have many to_* functions,但它缺少to_excel 函数。是否有更简单/更好的方法来完成此 sn-p 第 3 行中的导出?仅仅为了一个简单的 I/O 首先将 Series 转换为 DataFrame 感觉很笨拙:

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')

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以:

    1。从头构造一个DataFrame

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

    2。使用Series.to_frame()

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

    【讨论】:

    • 好的,所以答案实际上是“不”。但是to_frame 队列很好,为我手动更改 s.name 节省了一行,并且在我的上下文中看起来不像是丑陋的类型转换(pd.DataFrame 看起来像我)。
    • 如果你有兴趣,这可能是一个很好的第一次在 github 上的 pull request,虽然我不确定将单个列写入 Excel 表有多常见。
    • 如果第二次发生在我身上,我会考虑这样做;它只是在对 DataFrame 求和时发生在我身上。
    • 仅供参考,还有一个 DataFrame.squeeze() 方法可以将单个列 DataFrame 转换为 Series
    • 有人在 github 上创建过这个问题吗?我没找到。
    【解决方案2】:

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

    从 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')
    

    文件 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 /
    

    【讨论】:

    • 有没有办法把Series的写法从竖写改为横写,让索引作为列使用?
    • @KrzysztofSłowiński 不直接,只能通过s.to_frame().T.to_excel(...),使用DataFrame的转置操作。
    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-08-23
    • 1970-01-01
    • 2014-06-16
    • 2022-12-10
    • 1970-01-01
    • 2014-05-22
    相关资源
    最近更新 更多