0

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)   

1 Answer 1

1

After running your code once, you've already converted the values to np.floats so running a str.replace again will definitely as fail, as expected.

If you want to do these operations multiple times, I would recommend that you create copies of your data using df.copy().

Example

original_df = pd.DataFrame({'university': ['harvard', 'cambridge', 'GT'],
                 'international_students': ['28%', '33%', '55%']},
                 index=['0', '1', '2'])

# use this copy for your operations involving using the international_student field
# as floats
odf_cp1 = original_df.copy()
odf_cp1['international_students'] = odf_cp1['international_students'].str.replace('%', '')
odf_cp1['international_students'] = odf_cp1['international_students'].astype(np.float)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Onel. Now I understand. Thank you for your help.
You're welcome. Since this solved your problem, go ahead and mark this as the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.