Issue
I am trying to convert string values from a column where the values look like this: $200, $6,000, etc. I want to convert these values to float and save them into a new column in my dataframe so I can compute aggregate statistics like .mean() for example.
my_df["Float Values"] = my_df["Value"].apply(lambda x: float(x[1:].replace(',','')) if x != "None" else 0)
But unfortunately I am getting this error:
TypeError: 'float' object is not subscriptable
What am I doing wrong here?
Solution
maybe there are NaN
use following code:
my_df["Float Values"] = my_df["Value"].str[1:].str.replace(',', '').astype('float').fillna(0)
make reproducible example
import pandas as pd
s = pd.Series(['$200', '$3,000', float('nan')])
s
0 $200
1 $3,000
2 NaN
dtype: object
run your code:
s.apply(lambda x: float(x[1:].replace(',','')) if x != "None" else 0)
error:
TypeError: 'float' object is not subscriptable
use following code:
s.str[1:].str.replace(',', '').astype('float').fillna(0)
out:
0 200.0
1 3000.0
2 0.0
dtype: float64
Answered By - Panda Kim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.