Is it possible to add styling to the dataframe when you return dataframe function instead of printing the dataframe function?
Probably. But not really following. Can you give an example with code and how the cells are arranged of what you mean by âprinting the dataframe functionâ.
def Data_frame():
import pandas as pd
data = {âcol1â: [1, 2], âcol2â: [3, 4]}
df = pd.DataFrame(data)
return df
here we are returning df .How can we add styling to the columns?
Iâm still not probably following what you see as it seems this is covered in the Pandas documentation â Table Visualizationâ:
import pandas as pd
import numpy as np
def style_negative(v, props=''):
return props if v < 0 else None
def highlight_max(s, props=''):
return np.where(s == np.nanmax(s.values), props, '')
def stylized_Data_frame():
data = {'col1': [4, -11], 'col2': [2, 8]}
df = pd.DataFrame(data)
s_df = df.style.map(style_negative, props='color:red;')\
.map(lambda v: 'opacity: 20%;' if (v < 9) and (v > 4) else None)
s_df.apply(highlight_max, props='color:white;background-color:darkblue', axis=0)
return s_df
stylized_Data_frame()
That is your example adapted to an example in the documentation. As you didnât fully detail what you mean by styling you meant to add to the columns, I did something based on highlighting the maximum in the column, with some additional flair from the documentation examples thrown in.
Result:
Try it yourself without touching your own system, logging in, or installing things
Go here and click the launch binder
badge.
When the session comes up, open a new notebook and paste that code in and run it. You should see the same thing.
Very Minor:
Please make the job of those trying to help you easier by sharing useable code. For pasting code in so it is readable and useable in forums such as this, youâll want to learn about âblock code formattingâ here. (Or see about âfenced code blocksâ here. They are both the same thing if you look into the details. They just have slightly different terms used in the two locations.
If you read How do I ask a good question?, found referenced at the end of âGetting good answers to your questionsâ in this forum, youâll see the advice is always to try and run fresh the material provided in the post and only the post. (For simple code this can be more of a thought exercise once you do it a few times; however, for complex code it is always best to try. MyBinder-provided sessions, example of which I used under the âTry it yourselfâ section, are great for this.) Youâd see that the provided code didnât work in your case.
Itâs exactly what I wanted.Thanks for helping.