0
import pandas as pd  
DF1 = pd.DataFrame({'name': ['abc in first line of text', 'abc of second line of text', 'def on third line of text'], 'other': [10, 20, 30]})  
DF2 = DF1[DF1.name.str.startswith('abc')]  
DF2['name'] = [x.split('abc')[1][4:].title() for x in DF2['name']]  
print(DF2) 

Updating a column in a pandas dataframe using the code above gives the following warning:

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

The output is correct.

Any suggestions how to rewrite this code to prevent this warning?

René
  • 4,594
  • 5
  • 23
  • 52

1 Answers1

1

Using assign

DF2.assign(name=DF2.name.replace({'abc ':''},regex=True))
Out[46]: 
                     name  other
0   in first line of text     10
1  of second line of text     20

Or

DF2.assign(name=[x.split('abc')[1][4:].title() for x in DF2['name']])
Out[48]: 
                  name  other
0   First Line Of Text     10
1  Second Line Of Text     20
BENY
  • 317,841
  • 20
  • 164
  • 234
  • also, you can check this https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas – BENY Nov 22 '17 at 20:23