2

In a DF, I have a column that contains float, str, None and nan values.

I would like to round only the float values without affecting the others. I tried to use a mask to access only the float values, but did not succeed.

I would prefer it if the solution could use native pandas functions instead of iteration.

Sample of my data:

 index      Column A         Column B   
 1          57:24.1          98.67799997
 2          57:24.1          58.67799997
 3          57:53.8          95.66000009
 4          358:23.4         210.68099999
 5          None             35.10
 6          25.06778         None
 7          99999.565656     Abc
 8          abc              None
gmds
  • 19,325
  • 4
  • 32
  • 58
SBN
  • 51
  • 3

2 Answers2

0

How about this - it will check if the value is a float, if yes it will round to 1, else do nothing:

df["Column B"].apply(lambda x: round(x,1) if isinstance(x,float) else x)

Or if you want to apply this function to every cell in the dataframe:

df.applymap(lambda x: round(x,1) if isinstance(x,float) else x)

See also: Apply function to each cell in DataFrame

Kai Aeberli
  • 1,189
  • 8
  • 21
  • unfortunately, the first solution you proposed me returned me the Column B but not rounded & the second solution returned me the full DF without no changes (not rounded) – SBN Mar 30 '19 at 22:00
  • try replacing `float` with `np.float64`. It basically needs to be the exact type of float that you have in your dataframe. – Kai Aeberli Mar 30 '19 at 22:20
  • the first solution you gave did not change the output – SBN Apr 16 '19 at 21:30
  • the second returned me : AttributeError: 'Series' object has no attribute 'applymap' – SBN Apr 16 '19 at 21:30
  • can i check that "df" is a dataframe with more than 1 column? – Kai Aeberli Apr 17 '19 at 07:33
0

How about trying this. Might be a bit expensive but worth trying

df['Column B'] = [round(val,2) for val in df['column B'] if type(val)==float]
Sai Pardhu
  • 289
  • 1
  • 12