I have a dataset with 3 columns. In line1 of code, I replace the '%' with an empty value. In line2, I turn the international_students column string values into a float.
All good if I run the code once. However, if I run the code twice, I get an error: "Can only use .str accessor with string values, which use np.object_ dtype in pandas". I think it's because the column has turned into a float already.
How can I write the code so I can run it multiple times without the error?
df = pd.DataFrame({'university': ['harvard', 'cambridge', 'GT'],
'international_students': ['28%', '33%', '55%'],
index=['0', '1', '2']})
[line1]: df['international_students'] = df['international_students'].str.replace('%', '')
[line2]: df['international_students'] = df['international_students'].astype(np.float)