Сделайте сопоставление цветов градиента в указанном столбце в Pandas

Опубликовано: 27 Марта, 2022

Давайте посмотрим, как применить градиентное цветовое сопоставление для определенных столбцов фрейма данных Pandas. Мы можем сделать это с помощью функции Styler.background_gradient () класса Styler.

Syntax : Styler.background_gradient(cmap=’PuBu’, low=0, high=0, axis=0, subset=None)

Parameters :  

cmap : str or colormap (matplotlib colormap)

low, high : float (compress the range by these values.)

axis : int or str (1 or ‘columns’ for colunwise, 0 or ‘index’ for rowwise)

subset : IndexSlice (a valid slice for data to limit the style application to)

Returns :  self

Подход :

  • Модуль импорта Pandas
  • Создать DataFrame
  • Выбирайте конкретный столбец с умом с помощью функции style.background_gradient ()
  • Отобразить DataFrame

Разберемся на примерах:

Пример 1:

Create a DataFrame and gradient all the columns.

Python3



# importing pandas module
import pandas as pd
  
# Creating pandas DataFrame
df = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6],
                   "B": [3, -5, -6, 7, 3, -2],
                   "C": [-4, 5, 6, -7, 5, 4],
                   "D": [34, 5, 32, -3, -56, -54]})
  
# Displaying the original DataFrame
print("Original Array : ")
print(df)
  
# backgroung color mapping
print(" Dataframe - Gradient color:")
df.style.background_gradient()

Выход :

Пример 2:

Create a DataFrame and gradient the specific columns

Python3

# importing pandas module
import pandas as pd
  
# Creating pandas DataFrame
df = pd.DataFrame({"A": [1, 2, -3, 4, -5, 6],
                   "B": [3, -5, -6, 7, 3, -2],
                   "C": [-4, 5, 6, -7, 5, 4],
                   "D": [34, 5, 32, -3, -56, -54]})
  
# Displaying the original DataFrame
print("Original Array : ")
print(df)
  
# backgroung color mapping
print(" Dataframe - Gradient color:")
  
# df.style.background_gradient()
df.style.background_gradient(subset="B")

Выход :

If you want to change another column then

Python3

df.style.background_gradient(subset="D")

Выход :

,

Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.

Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.