📜  使用 apply() 突出显示 Pandas DataFrame 的特定列

📅  最后修改于: 2022-05-13 01:55:32.254000             🧑  作者: Mango

使用 apply() 突出显示 Pandas DataFrame 的特定列

让我们看看如何突出显示 Pandas DataFrame 的特定列。我们可以使用 Styler 类的apply()函数来做到这一点。

Styler.apply()

让我们通过例子来理解:

示例 1:

# importing pandas as pd 
import pandas as pd 
  
# creating the dataframe
df = pd.DataFrame({"A" : [14, 4, 5, 4, 1],
                   "B" : [5, 2, 54, 3, 2],
                   "C" : [20, 20, 7, 3, 8], 
                   "D" : [14, 3, 6, 2, 6],
                   "E" : [23, 45, 64, 32, 23]}) 
  
print("Original DataFrame :")
display(df)
  
# function definition
def highlight_cols(x):
      
    # copy df to new - original data is not changed
    df = x.copy()
      
    # select all values to green color
    df.loc[:, :] = 'background-color: green'
      
    # overwrite values grey color
    df[['B', 'C', 'E']] = 'background-color: grey'
      
    # return color df
    return df 
  
print("Highlighted DataFrame :")
display(df.style.apply(highlight_cols, axis = None))

输出 :

示例 2:

# importing pandas as pd 
import pandas as pd 
  
# creating the dataframe
df = pd.DataFrame({"Name" : ["Yash", "Ankit", "Rao"],
                   "Age" : [5, 2, 54]}) 
  
print("Original DataFrame :")
display(df)
  
# function definition
def highlight_cols(x):
      
    # copy df to new - original data is not changed
    df = x.copy()
      
    # select all values to yellow color
    df.loc[:, :] = 'background-color: yellow'
      
    # return color df
    return df 
  
print("Highlighted DataFrame :")
display(df.style.apply(highlight_cols, axis = None))

输出 :