Skip to content
- Tutorials
- Python
- Java
- Interview Corner
- Programming Languages
- Web Development
- CS Subjects
- DevOps And Linux
- Software and Tools
- School Learning
- Practice Coding Problems
- Go Premium
-
- Data preprocessing
- Data Manipulation
- Data Analysis using Pandas
- EDA
- Pandas Exercise
- Pandas AI
- Numpy
- Matplotlib
- Plotly
- Data Analysis
- Machine Learning
- Data science
Open In App
Next Article: Pandas Exercises and ProgramsLast Updated : 06 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report
As we know, the basic idea behind styling is to make more impactful for the end-user readability. We can make changes like the color and format of the data visualized in order to communicate insight more efficiently. For the more impactful visualization on the pandas DataFrame, generally, we DataFrame.style property, which returns styler object having a number of useful methods for formatting and visualizing the data frames.
Using DataFrame.style property
- df.style.set_properties: By using this, we can use inbuilt functionality to manipulate data frame styling from font color to background color.
Python3 # Importing the necessary libraries -->import pandas as pdimport numpy as np# Seeding random data from numpynp.random.seed(24)# Making the DataFramedf = pd.DataFrame({'A': np.linspace(1, 10, 10)})df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))], axis=1)# DataFrame without any stylingprint("Original DataFrame:\n")print(df)print("\nModified Stlying DataFrame:")df.style.set_properties(**{'background-color': 'black', 'color': 'green'})
Output:

- df.style.highlight_null : With the help of this, we can highlight the missing or null values inside the data frame.
Python3 # Replacing the locating value by NaN (Not a Number)df.iloc[0, 3] = np.nandf.iloc[2, 3] = np.nandf.iloc[4, 2] = np.nandf.iloc[7, 4] = np.nan# Highlight the NaN values in DataFrameprint("\nModified Stlying DataFrame:")df.style.highlight_null(null_color='red')
Output:

- df.style.highlight_min : For highlighting the minimum value in each column throughout the data frame.
Python3 # Highlight the Min values in each column print("\nModified Stlying DataFrame:")df.style.highlight_min(axis=0)
Output:

- df.style.highlight_max : For highlighting the maximum value in each column throughout the data frame.
Python3 # Highlight the Max values in each column print("\nModified Stlying DataFrame:")df.style.highlight_max(axis=0)
Output:

Using User-defined Function
- We can modify DataFrame using a user-defined function: With the help of this function, we can customizing the font color of positive data values inside the data frame.
Python3 # function for set text color of positive# values in Dataframesdef color_positive_green(val): """ Takes a scalar and returns a string with the css property `'color: green'` for positive strings, black otherwise. """ if val > 0: color = 'green' else: color = 'black' return 'color: %s' % colordf.style.applymap(color_positive_green)
Output:

Using Seaborn Library
- Using color palette for gradient fill in DataFrame: By importing the light palette of colors from the seaborn library, we can map the color gradient for the background of the data frame.
Python3 # Import seaborn libraryimport seaborn as sns# Declaring the cm variable by the # color palette from seaborncm = sns.light_palette("green", as_cmap=True)# Visualizing the DataFrame with set precisionprint("\nModified Stlying DataFrame:")df.style.background_gradient(cmap=cm).set_precision(2)
Output:

- Using color palette with highlight null or missing values: Here, we highlight the NaN values in red color with gradient color palette of seaborn.
Python3 # Highlight the NaN values in DataFrame # using seaborn color paletteprint("\nModified Stlying DataFrame:")df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red')
Output:

- Assemble Seaborn properties with DataFrame.style property: Customizing the seaborn color palette with highlight properties of a data frame for more impactful data visualization.
Python3 # Highlight the NaN values in DataFrame # using seaborn color palette as well as# min('lighblue') and max('blue') values # in each columnprint("\nModified Stlying DataFrame:")df.style.background_gradient(cmap=cm).set_precision(2).highlight_null('red').highlight_min(axis=0, color='lightblue').highlight_max(axis=0, color='blue')
Output:

Next Article
Pandas Exercises and Programs
Nnight_fury1
Improve
Article Tags :
- Python
- Python-pandas
- Python pandas-dataFrame
- pandas-dataframe-program
Practice Tags :
- python
Similar Reads
Pandas Exercises and Programs Pandas is an open-source Python Library that is made mainly for working with relational or labelled data both easily and intuitively. This Python library is built on top of the NumPy library, providing various operations and data structures for manipulating numerical data and time series. Pandas is 6 min read Different ways to create Pandas Dataframe It is the most commonly used Pandas object. The pd.DataFrame() function is used to create a DataFrame in Pandas. There are several ways to create a Pandas Dataframe in Python.Example: Creating a DataFrame from a DictionaryPythonimport pandas as pd # initialize data of lists. data = {'Name': ['Tom', 7 min readPandas DataFrame Practice Exercises
Pandas Dataframe Rows Practice Exercise
Pandas Dataframe Columns Practice Exercise
Pandas Series Practice Exercise
Pandas Date and Time Practice Exercise
DataFrame String Manipulation
Accessing and Manipulating Data in DataFrame
DataFrame Visualization and Exporting
top_of_element && top_of_screen < bottom_of_element) || (bottom_of_screen > articleRecommendedTop && top_of_screen < articleRecommendedBottom) || (top_of_screen > articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); });});window.isReportArticle = false;function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return;} if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); }} function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove();}function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu"));}function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none";}function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show");}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy







