Home > Enterprise >  Pandas - how to convert objects to float values?
Pandas - how to convert objects to float values?

Time:01-07

I am working with a pandas dataframe of football players. There is a column with the value of each player. The problem is the type of this column is an object and I want to convert it to float64. How can I do it? The variable is Release clause.

df_fifa['Release Clause']
0        €226.5M
1        €127.1M
2        €228.1M
3        €138.6M
4        €196.4M
          ...   
18202      €143K
18203      €113K
18204      €165K
18205      €143K
18206      €165K
Name: Release Clause, Length: 18207, dtype: object

I want to convert it to the complete number. E.g. €200M to 200.000.000 and €200k to 200.000.

I know the funcion should be

df_fifa['Release Clause'].astype(str).astype(int)

But first I should remove €, M & k. I tried this for removing but it didn't work

df_fifa['Release Clause'] = df_fifa['Release Clause'].replace("€","")

Anyone knows how to do it?

Thank you!

CodePudding user response:

Convert your symbol , K and M to '', * 1e3 and * 1e6 and evaluate your expression with pd.eval:

mapping = {'€': '', 'K': ' * 1e3', 'M': ' * 1e6'}

df_fifa['Release Clause'] = \
    pd.eval(df_fifa['Release Clause'].replace(mapping, regex=True))
print(df_fifa)

# Output
       Release Clause
0         226500000.0
1         127100000.0
2         228100000.0
3         138600000.0
4         196400000.0
18202        143000.0
18203        113000.0
18204        165000.0
18205        143000.0
18206        165000.0
  •  Tags:  
  • Related