【问题标题】:Missing data when exporting data frame from pandas to excel将数据框从 pandas 导出到 excel 时丢失数据
【发布时间】:2019-05-24 04:09:32
【问题描述】:

我创建了一个程序来使用 pandas 从 excel 文件中删除重复的行。成功完成后,我将新数据从 pandas 导出到 excel,但是新的 excel 文件似乎缺少数据(特别是涉及日期的列)。它只是在行上显示“##########”,而不是显示实际数据。

代码:

import pandas as pd
data = pd.read_excel('test.xlsx')
data.sort_values("Serial_Nbr", inplace = True)
data.drop_duplicates(subset ="Serial_Nbr", keep = "first", inplace = True)
data.to_excel (r'test_updated.xlsx')

导出前后:

date                            date

2018-07-01                  ##########    
2018-08-01                  ##########    
2018-08-01                  ##########

【问题讨论】:

  • 你能在 python shell 中看到数据吗?
  • 是的,我能看到

标签: excel python-3.x pandas


【解决方案1】:

表示单元格宽度无法显示数据,尝试扩大单元格宽度。

单元格的宽度太窄:

扩大单元格宽度后:

要正确导出到带有日期时间的excel,您必须添加excel导出的格式代码:

import pandas as pd

data = pd.read_excel('Book1.xlsx')
data.sort_values("date", inplace = False)
data.drop_duplicates(subset ="date", keep = "first", inplace = True)

#Writer datetime format
writer = pd.ExcelWriter("test_updated.xlsx",
                        datetime_format='mm dd yyyy',
                        date_format='mmm dd yyyy')

# Convert the dataframe to an XlsxWriter Excel object.
data.to_excel(writer, sheet_name='Sheet1')
writer.save()

【讨论】:

    【解决方案2】:

    ########## 在单元格的宽度太小而无法显示其内容时显示。您需要增加单元格的宽度或减少其内容

    【讨论】:

      【解决方案3】:

      关于原始数据查询,我同意ALFAFA的回复。
      在这里,我尝试调整列大小,以便最终用户无需在 xls 中手动执行相同操作。

      步骤如下:

      • 获取列名(根据 xls,列名以“A”、“B”、“C”等开头)
      colPosn = data.columns.get_loc('col#3')   # Get column position
      xlsColName = chr(ord('A')+colPosn)        # Get xls column name (not the column header as per data frame). This will be used to set attributes of xls columns
      
      • 通过获取列中最长字符串的长度来调整列“col#3”的宽度
      maxColWidth = 1 + data['col#3'].map(len).max()  # Gets the length of longest string of the column named 'col#3' (+1 for some buffer space to make data visible in the xls column)
      
      • 使用 column_dimensions[colName].width 属性增加 xls 列的宽度
      data.to_excel(writer, sheet_name='Sheet1', index=False) # use index=False if you dont need the unwanted extra index column in the file
      sheet = writer.book['Sheet1']
      sheet.column_dimensions[xlsColName].width = maxColWidth # Increase the width of column to match with the longest string in the column
      writer.save()
      
      • 将 ALFAFA 帖子的最后两行替换为上述块(以上所有部分),以获得针对“col#3”调整的列宽

      【讨论】:

        猜你喜欢
        • 2016-07-06
        • 1970-01-01
        • 1970-01-01
        • 2011-03-11
        • 1970-01-01
        • 1970-01-01
        • 2018-06-24
        • 1970-01-01
        • 2020-09-27
        相关资源
        最近更新 更多