【问题标题】:Can't write dataframe to excel after using groupby function in pandas在熊猫中使用 groupby 函数后无法将数据框写入 excel
【发布时间】:2015-06-15 10:02:18
【问题描述】:

将 Excel 文件导入为数据框:

import pandas as pd

ImportExcelAllDataFlow =pd.read_excel("TmeSpatialFromCenter.xlsx")

aa=ImportExcelAllDataFlow.groupby(['Source', 'TimeFlowContext']).size()

我想将“aa”数据框写入 excel。我使用下面的代码来做到这一点。但它不起作用。

TimeSpatialCount.to_excel(TimeSpatialCount.xlsx, sheet_name='sheet1' header=False)

谁能告诉我写这个的正确方法吗?

提前致谢。

【问题讨论】:

  • Define doesn't work 例如,如果您将文件类型更改为.xls,它是否也有效?

标签: python pandas spyder


【解决方案1】:

我想将“aa”数据框写入 excel。

大概这意味着你要写:

aa.to_excel("TimeSpatialCount.xlsx", sheet_name='sheet1' header=False)

您将 DataFrame aa 写入文件 "TimeSpatialCount.xls"

【讨论】:

  • 感谢您的回复。我在这里发布了一个错误。你在写。但这不是问题。我收到以下错误:getattr 中的文件“C:\Users\mdr\Anaconda\lib\site-packages\pandas\core\generic.py”,第 1843 行(类型(self) .__name__, name)) AttributeError: 'Series' object has no attribute 'to_excel' 如果我导入一个 excel 文件并写入该文件,它正在工作。但是在使用 group by function 之后,它就不起作用了。
  • @mizanbuet 您只能将 DataFrame 写入 excel,而不是 Series。您需要将 aa 转换为 DataFrame,例如aa.to_frame().to_excel(...)
  • 太棒了!这是工作。我想使用 groupby 函数我会直接得到数据帧。非常感谢。
猜你喜欢
  • 2016-10-09
  • 2013-12-19
  • 2021-04-30
  • 2019-03-21
  • 2014-03-28
  • 2021-07-22
  • 2017-08-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多