Skip to content Skip to sidebar Skip to footer

Change Pandas String Column With Commas Into Float

I ran the code: df['VotesPerYear'] = df['Votes']/df['Years'] and received the error: 'TypeError: unsupported operand type(s) for /: 'unicode' and 'float'' df['Votes'] is a strin

Solution 1:

You could use str.replace to change , to nothing and then convert column to float with astype method:

df["VotesPerYear"] = df["Votes"].str.replace(",", "").astype(float) / df["Years"]

Solution 2:

If each element in df['Votes'] is of the form u'x,xxx,xxx.xx' for example, we can do:

    df["VotesPerYear"] = df["Votes"].map(lambda x: float(''.join(x.split(',')))) / df["Years"]

Post a Comment for "Change Pandas String Column With Commas Into Float"