Home > Back-end >  how to use % in pandas while comparing a row to some value?
how to use % in pandas while comparing a row to some value?

Time:09-29

Like here i want those all rows which have GDP growth of more than 5% The values of "GDP growth (annual %)" are in a form of like 5.15%, 4.56%, 3.45% etc. So how should i compare this column with 5%?

import pandas as pd
eco = pd.read_excel("/home/n/Downloads/economies.xlsx")
top_five = eco[eco["GDP growth (annual %)"].to_string() > 5

Dataset

CodePudding user response:

You could slice the str datatype then cast it to float before performing your numerical comparison.

import pandas as pd

eco = pd.DataFrame([["5.3%"],["2.4%"]], columns=["GDP growth (annual %)"])
eco[eco['GDP growth (annual %)'].str[0:-1].astype('float') > 5]
  • Related