1

My data frame looks like this.

 a           d         e
0 BTC  31913.1123   -6.5%
1 ETH   1884.1621  -18.8%
2 USDT     1.0       0.1%
3 BNB    294.0246   -8.4%
4 ADA      1.0342  -14.3%
5 XRP      1.1423  -10.5%

On column d, I want to round the floats in column d to a whole number if it is greater than 10. If it is less than 10, I want to round it to 2 decimal places. This is the code I have right now df1['d'] = df1['d'].round(2). How do I had a conditional statement to this code to have it round based on conditions?

3 Answers3

0

Use numpy.where:

df1['d'] = np.where(df1['d'] < 10, df1['d'].round(2), df1['d'].round())
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
0

https://stackoverflow.com/a/31173785/7116645

Taking reference from above answer, you can simply do like following

df['d'] = [round(x, 2) if x > 10 else x for x in df['d']]
hp77
  • 75
  • 1
  • 2
  • 10
0

You can use simple statements like this:

df1['d'][df1['d']>10]=df1['d'][df1['d']>10].round()
df1['d'][df1['d']<10]=df1['d'][df1['d']<10].round(2)
ArunRaj131
  • 21
  • 4