从Pandas写入Excel时设置默认数字格式

时间:2018-06-27 17:24:02

标签: python python-3.x pandas openpyxl xlsxwriter

从Pandas数据框中写入Excel时,我希望设置默认数字格式。这可能吗?

我可以使用以下设置默认的date / datetime_format,但是找不到设置默认数字格式的方法。

writer = pd.ExcelWriter(f'{file_variable}.xlsx', engine='xlsxwriter',datetime_format='MM/DD/YYYY')

否则,我假设我将不得不为变量分配工作表,并遍历指定列的行以设置数字格式。

2 个答案:

答案 0 :(得分:4)

我得到了这种格式,浮点数到小数点后一位。

data = {'A Prime': {0: 3.26,  1: 3.24,  2: 3.22,  3: 3.2,  4: 3.18,  5: 3.16,
  6: 3.14,  7: 1.52,  8: 1.5,  9: 1.48,  10: 1.46,  11: 1.44,  12: 1.42},
 'B': {0: 0.16608,  1: 0.16575,  2: 0.1654,  3: 0.16505999999999998,  4: 0.1647,  5: 0.16434,  6: 0.16398,  7: 0.10759,  8: 0.10687,  9: 0.10614000000000001,
  10: 0.10540999999999999,  11: 0.10469,  12: 0.10396}, 'Proto Name': {0: 'Alpha',
  1: 'Alpha',  2: 'Alpha', 3: 'Alpha',  4: 'Alpha',  5: 'Alpha',  6: 'Alpha',  7: 'Bravo',  8: 'Bravo',  9: 'Bravo',  10: 'Bravo',  11: 'Bravo',  12: 'Bravo'}}

import pandas as pd
df = pd.DataFrame(data)


    A Prime B       Proto Name
0   3.26    0.16608 Alpha
1   3.24    0.16575 Alpha
2   3.22    0.16540 Alpha
3   3.20    0.16506 Alpha
4   3.18    0.16470 Alpha
5   3.16    0.16434 Alpha
6   3.14    0.16398 Alpha
7   1.52    0.10759 Bravo
8   1.50    0.10687 Bravo
9   1.48    0.10614 Bravo
10  1.46    0.10541 Bravo
11  1.44    0.10469 Bravo
12  1.42    0.10396 Bravo

writer = pd.ExcelWriter(r'c:\temp\output.xlsx')
# This method will truncate the data past the first decimal point
df.to_excel(writer,'Sheet1',float_format = "%0.1f")
writer.save()

enter image description here

但是可惜的是,并非所有情况都如此-说出更大的数字和成千上万的分隔符并不令人高兴

df.to_excel(writer,'Sheet1',float_format = ":,")

但是以下方法似乎可行

data = {'A Prime': {0: 326000,  1: 3240000}}
df = pd.DataFrame(data)

    A Prime
0   326000
1   3240000

writer = pd.ExcelWriter(r'c:\temp\output.xlsx')
df.to_excel(writer,'Sheet1')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '#,##0.00'})
worksheet.set_column('B', 18, format1)
#Alternatively, you could specify a range of columns with 'B:D' and 18 sets the column width
writer.save()

enter image description here

全部取自http://xlsxwriter.readthedocs.io/working_with_pandas.html

答案 1 :(得分:2)

对于它的价值以及因为该问题也被标记为openpyxl而言,您还可以在openpyxl中编辑整个工作簿的默认样式。这对于数字格式可能是有意义的,但是如果更改字体大小之类的内容,可能会产生意想不到的后果,因为会影响其他GUI元素。如果谨慎使用以下内容,则应该可以使用。

wb._named_styles['Normal'].number_format = '#,##0.00'