2

I have a data frame with the columns Name and name.

And I'm doing this:

for i in range(len(df)):
    if (some condition):
        df['name'][i] = df['Name'][i]

But I get this warning:

A value is trying to be set on a copy of a slice from a DataFrame

And also it takes a while to run, it's that related with the warning?

How should I do it?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Luis Ramon Ramirez Rodriguez
  • 9,591
  • 27
  • 102
  • 181

2 Answers2

2

You can try loc:

df.loc[df['name'].notnull() , 'Name'] = df['name']

And very nice explanation of SettingWithCopyWarning.

So generally:

df.loc[some condition , 'Name'] = df['name']
Community
  • 1
  • 1
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
1

You don't want to use chained assignments. You should use .loc:

condition = ... # something that identifies the relevant rows.
df.loc[condition, 'Name'] = df.loc[condition, 'name']

Refer to this SO post for more information.

And this is the link to the relevant Pandas documentation "Why does the assignment when using chained indexing fail!".

Community
  • 1
  • 1
Alexander
  • 105,104
  • 32
  • 201
  • 196