How to format float values to 2 decimal place in a dataframe except one column of the dataframe

Hi, i am trying to format the float values to 2 decimal place after replacing NA values with columns mean() and trying to keep the ID column without any decimal place, but getting error in streamlit. Can anyone help me in this.

My Steps:
1. Read the dataframe df
2. created a new dataframe as x without the β€˜ID’ column
3. Replace the NA values with it’s column mean() and stored back to x
4. Printing the dataframe x without β€˜ID’ column and formated to 2 decimal place in streamlit
5. Trying to concat the β€˜ID’ column of df i.e. df[β€œID”] with the dataframe x and trying to print in streamlit but getting error and showing different type.

I have attached my dataset also.

My Code:

x = df.iloc[:,1:]
x.replace(np.nan,x.mean(),inplace = True)
x = x.style.format("{:.2}")

st.write(x)

st.write(type(x))
st.write(type(df))

result = pd.concat([df["ID"],x],axis = 1)

st.write(result)

My Dataframe:

ID Position Marks
4 5.7680 56.4000
5 56.4000
6 5.7680 56.4000
7 5.7680 56.4000
8 7.2680 56.4000
9 5.7680 56.4000
10 5.7680 56.4000
11 5.7680
12 5.7680 56.4000
13 5.7680 56.4000
14 56.4000
15 5.7680 56.4000
16 5.9680 56.4000
17 5.7680 56.4000
18 2.7680 56.4000
19 5.7680 56.4000
20 5.7680
21 5.7680 56.4000
22 5.7680 56.4000
23 5.7680 56.4000

You are doing a concat of a Regular DataFrame and a Styler object. Pandas doesn’t support that
Applying the Styler needs to be the last thing you do, in the st.write() call. Use the subset parameter of style.format() to specify the columns.

2 Likes

Hi, this works only for numeric value, if β€˜ID’ column have alpha-numeric value then it will not work out. For numeric value we can write as below:

st.write(df.style.format("{:.2}"))

1 Like

This is a good way to solve the issue. I did the following which works well.

st.dataframe(df.style.format(subset=['Position', 'Marks'], formatter="{:.2f}"

Hope this helps!

5 Likes