0

I am totally new to Python (and pandas). I really tried to solve this problem, however, I couldn't solve it without getting the following warning:

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

I have two columns containing the first name and last name of a person. What I'm looking for is a way to add a new column to my data frame df containing the full name. This following code worked with warning:

df['Full Name'] = df['First Name'] + " " + df['Last Name']

Next, I tried

df.loc[:,'Full Name'] = df.loc[:,['First Name']] + " " + df.loc[:,['Last Name']],

which is invalid.

user
  • 5,370
  • 8
  • 47
  • 75
Patrick Balada
  • 1,330
  • 1
  • 18
  • 37

1 Answers1

0

First, you probably want to do

df.loc[:,'Full Name'] = df.loc[:,'First Name'].astype(str) + " " + df.loc[:,'Last Name'].astype(str)

or

df.loc[:,'Full Name'] = df.loc['First Name'].astype(str) + " " + df.loc['Last Name'].astype(str)

(.astype(str) may be too much in ur case)

then, you will probably still receive the warning for the reasons you can see in the message (check out this answer Pandas still getting SettingWithCopyWarning even after using .loc)

A short answer here is to write

 df.is_copy=False
 df.loc[:,'Full Name'] = df.loc[:,'First Name'].astype(str) + " " + df.loc[:,'Last Name'].astype(str)
Community
  • 1
  • 1
JoeyZhao
  • 514
  • 5
  • 12