使用Pandas样式将数千个分隔符添加到具有空字符串的DataFrame中

时间:2016-11-27 23:03:26

标签: python pandas dataframe ipython

这是this的后续问题。

使用Pandas Style,我设法将数据框中的所有值格式化为逗号为千位分隔符的值。但是,如果数据框中有空字符串,则格式化将失败。

基本上,我的目标是从enter image description here转换为:enter image description here

任何人都可以帮我吗?

这是我到目前为止的代码:

import pandas as pd
from IPython.display import HTML

styles = [
    hover(),
    dict(selector = "th",
         props = [("font-size", "110%"),
                  ("text-align", "left"),
                  ("background-color", "#cacaca")
                 ]
        )
    ]

column_01 = ["", 2000000000, "", 21000000, 3000]
df = pd.DataFrame(column_01)

int_frmt = lambda x: "{:,}".format(x) # Integer
float_frmt = lambda x: "{:,.0f}".format(x) if x > 1e3 else "{:,.2f}".format(x) # Float
str_frmt = lambda x: "{:}".format(x) # <----- Added for empty strings but fails
frmt_map = {np.dtype("int64"): int_frmt,
            np.dtype("float64"): float_frmt,  
            np.dtype("S"): str_frmt # <----- Added for empty strings but fails
           }
frmt = {col: frmt_map[df.dtypes[col]] for col in df.columns if df.dtypes[col] in frmt_map.keys()}

html = (df.style.set_table_styles(styles).format(frmt))

html

1 个答案:

答案 0 :(得分:1)

使用NumPy,您可以创建一个功能来进行转换,vectorize()它。然后可以按如下方式将其应用于您的数据框:

import numpy as np

def thousands(x):
    try:
        return '{:,}'.format(int(x))
    except ValueError as e:
        return x

data = np.array(["","2000000000", "", "21000000", "3000"])
f_thousands = np.vectorize(thousands)
print f_thousands(data)

给你:

['' '2,000,000,000' '' '21,000,000' '3,000']    

这会尝试将条目转换为整数,然后使用格式的千位分隔符。如果转换失败,则返回传递的条目,例如,空白

有关详细信息,另请参阅Python的Format Specification Mini-Language

使用Pandas,可以按如下方式完成:

import pandas as pd

def thousands(x):
    try:
        return '{:,}'.format(int(x))
    except ValueError as e:
        return x

data = pd.DataFrame(["","2000000000", "", "21000000", "3000"])
print data.applymap(thousands)

给你:

               0
0               
1  2,000,000,000
2               
3     21,000,000
4          3,000