13

I have a dataframe in pandas containing datetime and float data.

time                         price1              price2
2018-02-01T00:00:00.000Z     1.4526547885        1.654775563

I need to convert the columns to string format such that the price1 and price2 columns shows number upto 4 decimal places and the time is displayed as: 01,02,2018 00:00:00

Any leads on this is appreciated. Thanks

2 Answers 2

15

You can use dt.strftime for formating datetimes and then custom format of floats:

df['time'] = df['time'].dt.strftime('%Y,%m,%d %H:%M:%S')

cols = ['price1','price2']
df[cols] = df[cols].applymap(lambda x: '{0:.4f}'.format(x))
print (df)
                  time  price1  price2
0  2018,02,01 00:00:00  1.4527  1.6548
Sign up to request clarification or add additional context in comments.

8 Comments

Is there a way to make the last two digits of price1 and price2 columns data to be bold and be of increased size?
I think not, it is not possible.
Possible solution is create html and modify it.
can you please share an example, if possible on how to do that
For single column you can use this: df['col_name'] = df['col_name'].apply(lambda x: '{0:.2f}'.format(x))
|
9

You can use the round method to show only 4 decimals. and use .apply(str) to convert it to string object

EX:

df["price1"] = df["price1"].round(4).apply(str)
df["price2"] = df["price2"].round(4).apply(str)

2 Comments

I need those to be converted to string type too. similar for datetime
This will not work as desired if decimal is shorter then the rounded number i.e. for value 1.45 you will get formatted string 1.45 where expected value is 1.4500 when rounding is 4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.