【问题标题】:How to keep the value with signs as number from dataframe after write into Excel?写入Excel后如何将带有符号的值保留为数据框中的数字?
【发布时间】:2020-03-18 08:52:26
【问题描述】:

我目前正在使用 XlsxWriter 将数据框输出到 Excel 文件。 我的数据框如下。

Num     Des     price   percentage
321     pencil  $23     24%
452     pen     $12     29%
444     key     $32     33%
111     eraser  $49     14%

我使用的美元和百分号是代码:

df['price'] = df['price'].apply(lambda x: format(x, '.0%')) 
df['percentage'] = df['percentage'].apply(lambda x: format(x, "${:20,.0f}"))

但是当我通过 XlsxWriter 将数据框输出到 Excel 后,带有符号的值变成了字符串。

有没有办法可以保留数字类型?

【问题讨论】:

  • 你可以添加一些新的格式供工作簿使用 "percent_format = workbook.add_format({'num_format': '0%'})"

标签: python excel pandas dataframe xlsxwriter


【解决方案1】:

不要使用 pandas 来格式化文件,使用它们来做他们最擅长的事情,使用 pandas 来处理数据,使用 xlsxwriter 来格式化。

所以你的代码应该是这样的:

import pandas as pd

# Create your dataframe
df = pd.DataFrame({'Num': [321,452,444,111],
                    'Des': ['pencil','pen','key','eraser'],
                    'price': [23,12,32,49],
                    'percentage': [24,29,33,14]})

# Divide by 100 the column with the percentages
df['percentage'] = df['percentage'] / 100

# Pass the df into the xlsxwriter
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1', index=False)
workbook = writer.book
worksheet = writer.sheets['Sheet1']

# Define the formats
cell_format1 = workbook.add_format({'num_format': '$#,##0'})
cell_format2 = workbook.add_format({'num_format': '0%'})

# Set the columns width and format
worksheet.set_column('C:C', 12, cell_format1)
worksheet.set_column('D:D', 12, cell_format2)

# Write the file
writer.save()

输出:

有关 xlsxwriter 格式类的更多信息,请查看here,它确实拥有您需要的一切。

【讨论】:

    猜你喜欢
    • 2016-04-18
    • 2020-06-12
    • 1970-01-01
    • 2019-12-29
    • 2020-01-19
    • 1970-01-01
    • 2022-07-26
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多