将方法应用于 pandas 数据框中的几个选定列

Blu*_*rry 5 python dataframe pandas

我想对数据框中的几列应用一些小方法。方法 color_negative 不能应用于带有字符串的列,因此我需要以某种方式跳过这些列。我可以想到两种方法来解决这个问题,但遗憾的是没有一种方法有效。

  • 在方法 1 中:

    我尝试将该方法逐一应用于每一列,通过使用数据帧的索引并将 while 循环的递增计数器设置为 1 来跳过第一列。执行此方法时,我收到错误,即“系列”对象没有属性“样式”,所以显然,我无法将方法应用于单个列。

  • 在方法 2 中:

    我尝试使用子集仅将该方法应用于具有数值的列,但我不确定是否正确使用子集。执行此方法时,我收到错误,“Styler”类型的对象没有len().

这是一个简化的例子:

import pandas as pd

d = {'col1': ['a', 'b'], 'col2': [21, 22], 'col3': [3, 51]}
df = pd.DataFrame(data=d)

def color_negative_red(val):
    color = 'black'
    if val < -1 : color = 'red'
    if val > 1 :  color = 'green'
    return 'color: %s' % color    
    
i=1
while i <= len(df):
    #Approach 1
    df.iloc[:, i] = df.iloc[:, i].style.applymap(color_negative_red)
    #Approach 2
    df = df.style.applymap(color_negative_red, subset = df.iloc[:, i])
    i+=1    

df
Run Code Online (Sandbox Code Playgroud)

有人建议如何解决这个问题吗?

mos*_*evi 5

您可以选择所需的列,然后applymap选择它们,如下所示:

column_names = ['name_a','name_b']
df[column_names] = df[column_names].applymap(my_func)
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你可以过滤掉字符串列

from numpy.core.multiarray import dtype

column_names = [name for name,col_type in df.dtypes.items() if col_type!=dtype('O')]
Run Code Online (Sandbox Code Playgroud)


jez*_*ael 2

您可以使用style.Styler.applywith进行填充DataFrame of stylesnumpy.select

d = {'col1': ['a', 'b'], 'col2': [21, 22], 'col3': [0, -51]}
df = pd.DataFrame(data=d)

def color_negative_red(x):
    #select only numeric columns
    x1 = x.select_dtypes(np.number)
    c1 = 'color: red'
    c2 = 'color: green'
    c3 = '' 
    #boolean masks
    m1 = x1 < -1
    m2 = x1 > 1
    #numpy array by conditions
    arr = np.select([m1, m2], [c1, c2], default=c3)
    df1 =  pd.DataFrame(arr, index=df.index, columns=x1.columns)
    #added strings columns filled by c3 string 
    df1 = df1.reindex(columns=x.columns, fill_value=c3)
    return df1

df.style.apply(color_negative_red, axis=None)
Run Code Online (Sandbox Code Playgroud)

图片