熊猫造型:导出数字格式到Excel

2024-04-19 00:28:28 发布

您现在位置:Python中文网/ 问答频道 /正文

当前的熊猫造型help page提到了这一点

The following pseudo CSS properties are also available to set excel specific style properties:

  • number-format 支持导出到excel

但是,没有给出任何工作示例,并且尝试调整提供的功能,没有让我了解以下内容:

import numpy as np
import pandas as pd

def format2zero(val):
    frmat  = '{0:,.0f}'
    return 'number-format: %s' % frmat


np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
               axis=1)
df.iloc[0, 2] = np.nan

df.style.\
    apply(format2zero).\
    to_excel('styled.xlsx', engine='openpyxl')

我知道这是相对较新的,如果有人让它工作的话?你知道吗


Tags: toimportformatnumberdataframedfstyleas
1条回答
网友
1楼 · 发布于 2024-04-19 00:28:28

我相信您已经将Excel术语用于number-format,而不是python术语。在Excel中,当您右键单击单元格并选择Format cells/Custom时,您将得到一些选项,您可以定义自己的选项。我认为#,##0是你想要得到的零位小数:

def format2zero(val):
    return 'number-format: #,##0'

IIUC您应该使用df.style.applymap而不是df.style.apply,因为您希望format2zero应用于每个单元格而不是每行或每列。你知道吗

当在Excel中查看时,在代码中进行这两个更改将提供以下输出:

    A   B   C   D   E
0   1   1       0  -1
1   2  -1  -1   1   0
2   3  -2   0   1   2
3   4   1   0   0   1
4   5   1   1   0   1
5   6  -1   1   1   0
6   7   0   1   0   2
7   8   0   1   0   1
8   9   2  -1   1  -2
9   10  0   1  -1   0

相关问题 更多 >