how do you style data frame in Pandas

2024/10/6 11:07:34

I have this data frame:

dfServer        Env.    Model   Percent_Utilized
server123     Prod     Cisco.       50
server567.    Prod     Cisco.       80
serverabc.    Prod     IBM.         100
serverdwc.    Prod     IBM.         45
servercc.     Prod      Hitachi.    25
Avg                                60server123Uat  Uat     Cisco.       40
server567u    Uat     Cisco.       30
serverabcu    Uat     IBM.         80
serverdwcu    Uat     IBM.         45
serverccu     Uat     Hitachi      15
Avg                               42

I need to apply style to this data frame based on Percent_Utilized column. I have this solution so far:

def color(val):if pd.isnull(val):returnelif val > 80:background_color = 'red'elif val > 50 and val <= 80:background_color = 'yellow'else:background_color = 'green'return 'background-color: %s' % background_colordef color_for_avg_row(row):styles = [''] * len(row)if row['Server'] == 'Avg':if row['Percent_Utilized'] > 80:color = 'background-color: red'elif row['Percent_Utilized'] > 50:color = 'background-color: yellow'else:color = 'background-color: green'styles = [color for _ in row.index]return pd.Series(styles, index=row.index)df_new = (df.style.apply(color_for_avg_row, axis=1).applymap(color, subset=["Percent_Utilized"]))df_new 

pd.isnull(val): line seem to skip over the values in color function. but now I get a different error:

  AttributeError: 'NoneType oject has no attribute 'rstrip'. 

I think when I try to style to to df_new, it is putting this error.

Answer

this worked:

def color(val):if pd.isnull(val):background_color = 'white'elif val > 80:background_color = 'red'elif val > 50 and val <= 80:background_color = 'yellow'else:background_color = 'green'return 'background-color: %s' % background_colordef color_for_avg_row(row):styles = [''] * len(row)if row['Server'] == 'Avg':if row['Percent_Utilized'] > 80:color = 'background-color: red'elif row['Percent_Utilized'] > 50:color = 'background-color: yellow'else:color = 'background-color: green'styles = [color for _ in row.index]return pd.Series(styles, index=row.index)df_new = (df.style.apply(color_for_avg_row, axis=1).applymap(color, subset=["Percent_Utilized"]))
https://en.xdnf.cn/q/119787.html

Related Q&A

Vacation price program Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Why did push of a Flask app to Heroku failed?

Im simply trying to push my Flask app to Heroku but I encountered the following error: remote: ERROR: Command errored out with exit status 1: remote: command: /app/.heroku/python…

How to navigate through HTMl pages that have paging for their content using Python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 6 years ago.Improve…

How to merge one list elements with another list elements in python? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

Display and play audio files

I am new to python, and Im trying to build a simple recording program. With the some help from my previous question, I was able to add a timestamp for each recorded fileEDIT:I did some research and dec…

Web Scraping BeautifulSoup - Next Page parsing

Im just learning web scraping & want to output the result of this website to a csv file https://www.avbuyer.com/aircraft/private-jets but am struggling with parsing the next pages here is my code (…

convert sum value to percentage by userid django

Im trying to convert the total sum to a percentage by userid but an error pops up when I try to run the following program. The error is: name mark is not definedBelow is my code for views.pydef attStud…

ValueError: Too many values to unpack

Task is to find,sort,and remove the student with type: "homework" and with the lowest score using MongoDB. I also tried to use toArray() function,but it gave an error. Now I try to move on in…

Pandas - Create dynamic column(s) from a single columns values

I have JSON data which I am planning after converting it to desired dataframe, will concat with another dataframe. Participant**row 1** [{roles: [{type: director}, {type: founder}, {type: owner}, {type…

How to automatically remove certain preprocessors directives and comments from a C header-file?

Whats a good way to remove all text from a file which lies between /* */ and #if 0 and corresponding #endif? I want to strip these parts from C headers. This is the code I have so far:For line in file…