Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new column in pandas df populated by True,False depending on whether a float column is a whole number (`float.is_integer`)

I have a pandas df where df['value'] is a series of floats.

  • Some of the floats will be whole numbers (like 25.0). I want to create a new column, df['is_it_whole'][i] with values 1 (or True) is the corresponding df['value'][i] is a whole number, 0 or False otherwise.
  • I know I can do a for loop, but I am wondering if there is any trick I can use to do it fast (I have a large df).
  • I tried using df['is_it_whole'] = df['value'].is_integer() but pandas series do not support the is_integer method, I am looking for something similar that would work.

Suggestions?

like image 650
user Avatar asked Jan 05 '23 03:01

user


1 Answers

import pandas as pd
df = pd.DataFrame([['A', 1], ['B', 2.5], ['C', 3.0], ['D', 3.2]], columns=['label', 'value'])
df['is_it_whole'] = df['value'].map(lambda x: x.is_integer())
df

  label  value is_it_whole
0     A    1.0        True
1     B    2.5       False
2     C    3.0        True
3     D    3.2       False
like image 54
Dennis Golomazov Avatar answered Jan 08 '23 09:01

Dennis Golomazov