【问题标题】:How to hide the rows index如何隐藏行索引
【发布时间】:2019-09-17 19:56:40
【问题描述】:

我想将此 DataFrame 写入没有索引值的 xlsx 文件。我该怎么做?

writer=pd.ExcelWriter(r"D:\pandas.xlsx")
today=datetime.datetime.today()
header = pd.MultiIndex.from_product([[today],["name","lastname","age"]])
data=pd.DataFrame(newList, columns=header)
data.to_excel(writer)
writer.save()

结果:

  2019-09-16 18:23:20.851291              
                        name  lastname age
0                        John  McBrain  22
1                     Patrick    Heszke 33
2                      Luk         Nans 21

我需要:

  2019-09-16 18:23:20.851291              
                        name  lastname age
                        John  McBrain  22
                     Patrick    Heszke 33
                         Luk      Nans 21

【问题讨论】:

  • to_excel 中有一个 index=False 参数;那是你需要的吗?否则print(df.to_string(index=False))呢?
  • 当我在 to_excel 中使用 index=False 时,出现错误(使用 MultiIndex 列写入 Excel 且没有索引 ('index'=False) 尚未实现)
  • 这很不幸。为了清楚起见,这里的目标是在没有索引的情况下写入 excel 文件,还是您只是想将此结果打印到某个控制台或文本文件?
  • 你也可以df.reset_index(drop=True).to_excel(index=False)?
  • df.reset_index(drop=True).to_excel(index=False) - 同样的错误。我需要把它写成 excel

标签: python pandas


【解决方案1】:

这是异常的解决方法:

NotImplementedError: Writing to Excel with MultiIndex columns and no index ('index'=False) is not yet implemented.

df.columns 是MultiIndex 时调用df.to_excel(writer, index=False) 时会出现这种情况。

import numpy as np
import pandas as pd

np.random.seed(2019)

def write_excel(df, path, *args, **kwargs):
    """
    Write df as an excel file to path, roughly similar to `df.to_excel` except that it handles
    `df` with MultiIndex columns and `index=False`.
    """
    writer = pd.ExcelWriter(path)

    header = pd.DataFrame(df.columns.to_list()).T
    header.to_excel(writer, header=False, *args, **kwargs)

    # Avoid the "NotImplementedError: Writing to Excel with MultiIndex columns"
    # exception by temporarily changing the columns to a single-level index
    orig_columns = df.columns
    df.columns = range(len(df.columns))
    df.to_excel(
        writer, startrow=len(header), header=False, *args, **kwargs
    )
    df.columns = orig_columns
    writer.save()

df = pd.DataFrame(np.random.randint(10, size=(5, 4)), columns=list("ABCD"))
df = df.set_index(list("AB")).unstack("B")
write_excel(df, r"/tmp/pandas.xlsx", sheet_name="Sheet1", index=False)    
print(df)

转换 DataFrame,df:

     C              D          
B    2    5    8    2    5    8
A                              
0  5.0  NaN  NaN  7.0  NaN  NaN
6  NaN  NaN  0.0  NaN  NaN  0.0
7  NaN  NaN  5.0  NaN  NaN  3.0
8  5.0  4.0  NaN  8.0  0.0  NaN

到一个看起来像的电子表格

【讨论】:

  • 可爱..非常有用:) +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-03
  • 2017-01-31
  • 1970-01-01
  • 2017-11-15
  • 2021-12-20
  • 1970-01-01
  • 2022-11-12
相关资源
最近更新 更多