Reputation: 1484
I have a dataframe:
Col1 Col2 Col3 Col4
AAA 30 0.00000005 0.00000000
BBB 0 0.00000000 0.00000000
CCC 55 3.00554440 0.00000000
df.dtypes
Col1 object
Col2 int64
Col3 float64
Col4 float64
I want to re-format the float
type column.
If the values in floats columns are "0" then set the format to integer "0". otherwise, ".6f".
Col1 Col2 Col3 Col4
AAA 30 0.000000 0
BBB 0 0 0
CCC 55 3.005544 0.000000
How can I reformat like this?
Upvotes: 0
Views: 329
Reputation: 75080
Based on what I gather , you can make your own display function and apply the same with df.style
float_cols= df.columns[df.dtypes.values==np.dtype('float64')]
def myformat(d):
d1 = pd.DataFrame(np.where(d==0,'.0f','.6f'),d.index,d.columns)
return d1
df.style.apply(myformat,axis=None,subset=float_cols)
Upvotes: 1
Reputation: 34066
Something like this:
In [1692]: cols = df.select_dtypes('float').columns
In [1694]: df[cols] = np.where(df.select_dtypes('float').eq(0), 0, df.select_dtypes('float').applymap(lambda x: round(x, 6)))
In [1695]: df
Out[1695]:
Col1 Col2 Col3 Col4
0 AAA 30 0.000000 0.0
1 BBB 0 0.000000 0.0
2 CCC 55 3.005544 0.0
Upvotes: 1