Pandas Styler

112
3
Jump to solution
08-17-2022 09:10 AM
TylerT
by
Occasional Contributor

I'm trying to pass conditional string formatting from a function back to style.format as shown here....

TylerT_0-1660752488025.png

Ultimately, I'm looking for the same results as above EXCEPT {:.3f}m should be 3.000m in the output displayed dataframe.  Any ideas?

Thank you,

Tyler

 

Here's the code for testing:

df = pd.DataFrame([[np.nan, 1.0, 'A'], [2.0, np.nan, 3.0]])
df
func = lambda s: 'STRING' if isinstance(s, str) else '{:.3f}m'
df.style.format({0: '{:.3f}m', 2: func}, na_rep='MISS')
0 Kudos
1 Solution

Accepted Solutions
dslamb2022
New Contributor II

I think you are missing the format function. 

'{:.3f}m'.format(s)

 

View solution in original post

3 Replies
dslamb2022
New Contributor II

I think you are missing the format function. 

'{:.3f}m'.format(s)

 

TylerT
by
Occasional Contributor

@dslamb2022 et al,

In the same vein, do you have any notion of how to set conditional formatting based on another column?  Let's say we have...

TylerT_0-1660762395172.png

and we want to produce this...

TylerT_1-1660762475625.png

where: if value in col 0 == 'A' then format float as '{:.3f}f' and if col 0 == 'B' then format as '{:.3f}m', using df.style.format() or other formatting/styler methods.

Thank you,

Tyler

0 Kudos
TylerT
by
Occasional Contributor

Thank you!

0 Kudos