I get an error when using .astype() with pandas

Question:

I get an error when trying to make a new df:

ERROR:

'A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead'

This is the code that gives the error:

df = pd.DataFrame(data)
new_df = df
bools = ['ind-debateclub', 'ind-programming_exp', 
'ind-international_exp',
'ind-entrepeneur_exp', 'ind-exact_study', 'decision']

for i in bools:
    new_df[i] = df[i].astype(int)
new_df.head()

I have tried it like this, but this yields the same error:

new_df[i] = df.loc[df[i].astype(int)]

The input looks like this:
DataFrame

Asked By: Worldy

||

Answers:

Try changing the new_df = df line to:

new_df = df.copy()

also change the .astype() line to:

new_df[i] = new_df[i].astype(int)
Answered By: gtomer
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.