首页 > 解决方案 > 过滤具有不同 dtype 单元格的列

问题描述

我最近问了一个关于为数据框的特定列应用 select_dtypes 的问题。

我有这个数据框,它的列上有不同的 dtypes(在这种情况下是 str 和 int)。

df = pd.DataFrame([
[-1, 3, 0],
[5, 2, 1],
[-6, 3, 2],
[7, '<blank>', 3 ],     
['<blank>', 2, 4],
['<blank>', '<blank', '<blank>']], columns='A B C'.split())

我想为字符串和整数创建不同的掩码。然后我将根据这些面具应用样式。

首先让我们定义一个函数来帮助我为不同的数据类型创建我的掩码。(感谢@jpp

def filter_type(s, num=True):
    s_new = pd.to_numeric(s, errors='coerce')
    if num:
        return s_new.notnull()
    else:
        return s_new.isnull()

那么我们的第一个掩码将是:

mask1 = filter_type(df['A'], num=False) # working and creating the bool values

第二个掩码将基于整数间隔:

mask2 = df['A'].between(7 , 0 , inclusive=False)    

但是当我运行 mask2 时,它给了我错误:

TypeError:'>' not supported between instances of 'str' and 'int'

我该如何克服这个问题?

注意:我想应用的样式如下:

def highlight_col(x):
    df=x.copy
    mask1 = filter_type(df['A'], num=False)
    mask2 = df['A'].between(7 , 0 , inclusive=False)
    x.loc[mask1, ['A', 'B', 'C']] = 'background-color: ""'
    x.loc[mask2, ['A', 'B', 'C']] = 'background-color: #7fbf7f'

标签: pythonpandasdataframestyling

解决方案


pd.DataFrame.loc用于设置值。您需要pd.DataFrame.style设置样式。此外,您可以使用try/except来识别数字比较何时失败。

这是一个最小的例子:

def styler(x):
    res = []
    for i in x:
        try:
            if 0 <= i <= 7:
                res.append('background: red')
            else:
                res.append('')
        except TypeError:
            res.append('')
    return res

res = df.style.apply(styler, axis = 1)

结果:

在此处输入图像描述


推荐阅读