Skip to main content
 首页 » 编程设计

python之Pandas 写入 excel : 1) blank row from index; 2) keep index daily

2025年05月04日10kerrycode

我过去一直使用 Stata 进行数据分析,但今天我一直在探索 pandas。我成功地复制了我在 Stata 中所做的一些分析,但我很难将其导出到 excel。

我使用 write_excel() 得到的例子

                         Column1  Column2 
    Date         
    2014-01-01 00:00:00  x        a 
    2014-01-02 00:00:00  y        b 
    2014-01-03 00:00:00  z        c 
  1. 我想对齐索引,使其与列标题对齐。基本上,我想将列标题保留在原处,但将所有内容上移一个单元格。

  2. 我希望我的索引只有日期 (YYYY-MM-DD) 而没有小时、分钟和秒(始终为 00:00:00)。如何将我的索引更改为只有日期?

非常感谢。

请您参考如下方法:

对我有用的是重置索引,使“日期”成为普通列,然后调用 dt 属性 date 仅分配回日期部分,写入 excel 时传递参数 index=False:

In [34]: 
 
df = df.reset_index() 
df['Date'] = df.Date.dt.date 
df 
Out[34]: 
         Date Column1 Column2 
0  2014-01-01       x       a 
1  2014-01-02       y       b 
2  2014-01-03       z       c 

然后

df.to_excel(r'c:\data\t.xlsx',index=False) 

这会在 excel 中产生以下结果: