I would like to create a function that will check a condition in a column?

Viewed 13

I'm just new to pandas dataframes and I have a column of values but the ones that are superior to 1000 are displayed like 1k and values less than 1000 are normally displayed. I need to make a function that will first will remove the 'k' if is in the field and if its not just return the value and after that I would need the value as a float.

the thing is that I dont know where to start. if you guys dont mind I could use some help its too many steps in just one function!

df['interviews'].head()

0    3.3k
1    2.5k
2    2.1k
3    1.1k
4     849

1 Answers

Just do it one step at a time. Pandas will do the looping for you, so you just worry about one value at a time.

import pandas as pd

sample = [
    [ "1.4k" ],
    [ "1k" ],
    [ "987" ],
    [ "876.4" ]
]

data = pd.DataFrame(sample, columns=['data'])
print(data)

def cvt(val):
    if val[-1] == 'k':
        return float(val[:-1]) * 1000
    return float(val)


data['data'] = data['data'].apply(cvt)
print(data)

Output:

    data
0   1.4k
1     1k
2    987
3  876.4
     data
0  1400.0
1  1000.0
2   987.0
3   876.4
Related