Отобразить фрейм данных Pandas в стиле тепловой карты
Библиотека Pandas на языке программирования Python широко используется из-за ее способности создавать различные типы структур данных, а также предлагает множество операций, выполняемых с числовыми данными и данными временных рядов. Отображая фрейм данных панды в стиле тепловой карты, пользователь получает визуализацию числовых данных. Он дает обзор всего фрейма данных, что позволяет очень легко понять ключевые моменты в фреймворке данных.
Тепловая карта представляет собой матричную двумерную фигуру, которая дает визуализацию числовых данных в виде ячеек. Каждая ячейка тепловой карты окрашена, а оттенки цвета представляют некоторую связь значения с фреймом данных. Ниже приведены некоторые способы отображения фрейма данных Panda в стиле тепловой карты.
Рассмотрим этот фрейм данных в качестве примера:

Method 1 : By using Pandas library
In this method, the Pandas library will be used to generate a dataframe and the heatmap for it. The cells of the heatmap will display values corresponding to the dataframe. Below is the implementation.
# Python program to generate a heatmap# which displays the value in each cell # corresponding to the given dataframe # import required librariesimport pandas as pd # defining index for the dataframeidx = ["1", "2", "3", "4"] # defining columns for the dataframecols = list("ABCD") # entering values in the index and columns # and converting them into a panda dataframedf = pd.DataFrame([[10, 20, 30, 40], [50, 30, 8, 15], [25, 14, 41, 8], [7, 14, 21, 28]], columns = cols, index = idx) # displaying dataframe as an heatmap # with diverging colourmap as virdisdf.style.background_gradient(cmap ="viridis") .set_properties(**{"font-size": "20px"}) |
Выход : 
Method 2 : By using matplotlib library
In this method, the Panda dataframe will be displayed as a heatmap where the cells of the heatmap will be colour-coded according to the values in the dataframe. A colour bar will be present besides the heatmap which acts as a legend for the figure. Below is the implementation.
# Python program to generate a heatmap # which represents panda dataframe# in colour coding schemes # import required librariesimport matplotlib.pyplot as pltimport pandas as pd # Defining index for the dataframeidx = ["1", "2", "3", "4"] # Defining columns for the dataframecols = list("ABCD") # Entering values in the index and columns # and converting them into a panda dataframedf = pd.DataFrame([[10, 20, 30, 40], [50, 30, 8, 15], [25, 14, 41, 8], [7, 14, 21, 28]], columns = cols, index = idx) # Displaying dataframe as an heatmap# with diverging colourmap as RdYlBuplt.imshow(df, cmap ="RdYlBu") # Displaying a color bar to understand# which color represents which range of dataplt.colorbar() # Assigning labels of x-axis # according to dataframeplt.xticks(range(len(df)), df.columns) # Assigning labels of y-axis # according to dataframeplt.yticks(range(len(df)), df.index) # Displaying the figureplt.show() |
Выход : 
Method 3 : By using Seaborn library
In this method, a heatmap will be generated out of a Panda dataframe in which cells of the heatmap will contain values corresponding to the dataframe and will be color-coded. A color bar will also present besides the heatmap which acts as a legend for the figure. Below is the implementation.
# Python program to generate heatmap which # represents panda dataframe in color-coding schemes# along with values mentioned in each cell # import required librariesimport pandas as pdimport seaborn as sns % matplotlib inline # Defining figure size # for the output plot fig, ax = plt.subplots(figsize = (12, 7)) # Defining index for the dataframeidx = ["1", "2", "3", "4"] # Defining columns for the dataframecols = list("ABCD") # Entering values in the index and columns # and converting them into a panda dataframedf = pd.DataFrame([[10, 20, 30, 40], [50, 30, 8, 15], [25, 14, 41, 8], [7, 14, 21, 28]], columns = cols, index = idx) # Displaying dataframe as an heatmap # with diverging colourmap as RdYlGnsns.heatmap(df, cmap ="RdYlGn", linewidths = 0.30, annot = True) |
Output :
If the uppermost and the lowermost row of output figure does not appear with proper height then add below two lines after the last line of the above code.
bottom, top=ax.get_ylim()ax.set_ylim(bottom+0.5, top-0.5)
Method 4 : Generating correlation matrix using Panda library
A correlation matrix is a special kind of heatmap which display some insights of the dataframe. The cells of this heatmap display the correlation coefficients which is the linear historical relationship between the variables of the dataframe. In this method only Pandas library is used to generate the correlation matrix. Below is the implementation.
# Python program to generate heatmap # which represents correlation between # columns of panda dataframe # import required librariesimport pandas as pd # Defining index for the dataframeidx = ["1", "2", "3", "4"] # Defining columns for the dataframecols = list("ABCD") # Entering values in the index and columns # and converting them into a panda dataframedf = pd.DataFrame([[10, 20, 30, 40], [50, 30, 8, 15], [25, 14, 41, 8], [7, 14, 21, 28]], columns = cols, index = idx) # generating pairwise correlationcorr = df.corr() # Displaying dataframe as an heatmap # with diverging colourmap as coolwarmcorr.style.background_gradient(cmap ="coolwarm") |
Выход : 
Method 5 : Generating correlation matrix using Seaborn library
The correlation matrix can also be generated using Seaborn library. The cells of the generated heatmap will contain the correlation coefficients but the values are round off unlike heatmap generated by Pandas library. Below is the implementation.
# Python program to generate a heatmap # which represents the correlation between # columns of panda dataframe # import required librariesimport pandas as pdimport seaborn as sn # Defining figure size # for the output plot fig, ax = plt.subplots(figsize = (12, 7)) # Defining index for the dataframeidx = ["1", "2", "3", "4"] # Defining columns for the dataframecols = list("ABCD") # Entering values in the index and columns # and converting them into a panda dataframedf = pd.DataFrame([[10, 20, 30, 40], [50, 30, 8, 15], [25, 14, 41, 8], [7, 14, 21, 28]], columns = cols, index = idx) df = pd.DataFrame(df, columns =["A", "B", "C", "D"]) corr = df.corr()sn.heatmap(corr, annot = True) |
Выход : 
If the uppermost and the lowermost row of output figure does not appear with proper height then add below two lines after the last line of the above code.
bottom, top = ax.get_ylim()ax.set_ylim(bottom + 0.5, top - 0.5) |
Внимание компьютерщик! Укрепите свои основы с помощью базового курса программирования Python и изучите основы.
Для начала подготовьтесь к собеседованию. Расширьте свои концепции структур данных с помощью курса Python DS. А чтобы начать свое путешествие по машинному обучению, присоединяйтесь к курсу Машинное обучение - базовый уровень.