Reputation: 955
I have the following DataFrame:
races_dict = {
"grand_prix": [
'Australia', 'Bahrain', 'China',
'Azerbaijan', 'Spain', 'Monaco',
'Canada', 'France', 'Austria',
'Great Britain', 'Germany', 'Hungary',
'Belgium', 'Italy', 'Singapore',
'Russia', 'Japan', 'Mexico',
'United States', 'Brazil',
],
"laps": [
58, 57, 56,
51, 66, 78,
70, 53, 71,
52, 64, 70,
44, 53, 61,
53, 52, 71,
56, 71,
],
'winner': [
'Valtteri Bottas', 'Lewis Hamilton', 'Lewis Hamilton',
'Valtteri Bottas', 'Lewis Hamilton', 'Lewis Hamilton',
'Lewis Hamilton', 'Lewis Hamilton', 'Max Verstappen',
'Lewis Hamilton', 'Max Verstappen', 'Lewis Hamilton',
'Charles Leclerc', 'Charles Leclerc', 'Sebastian Vettel',
'Lewis Hamilton', 'Valtteri Bottas', 'Lewis Hamilton',
'Valtteri Bottas', 'Max Verstappen'
],
'car': [
'MERCEDES', 'MERCEDES', 'MERCEDES',
'MERCEDES', 'MERCEDES', 'MERCEDES',
'MERCEDES', 'MERCEDES', 'RED BULL RACING HONDA',
'MERCEDES', 'RED BULL RACING HONDA', 'MERCEDES',
'FERRARI', 'FERRARI', 'FERRARI',
'MERCEDES', 'MERCEDES', 'MERCEDES',
'MERCEDES', 'RED BULL RACING HONDA'
]
}
df = pd.DataFrame(races_dict)
df
I want to replace RED BULL RACING HONDA
with HONDA
. I believe I get the right answer when I use either of the following:
df.car[df.car=='RED BULL RACING HONDA'] = 'HONDA'
df.car.loc[df.car=='RED BULL RACING HONDA'] = 'HONDA'
but I receive the following warning:
SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
When I use the following:
df.car = df.car.replace('RED BULL RACING HONDA', 'HONDA')
I receive no warnings/errors.
My question is, which of the above is the preferred way to replace a value based on a condition in pandas?
Upvotes: 1
Views: 166
Reputation: 862481
I think it depends of data, if need repalce multiple values use dictionary like:
df.car = df.car.replace({'RED BULL RACING HONDA': 'HONDA', 'aa':'bb'})
For avoid your error need specified column car
inside DataFrame.loc
, but if need multiple replacement better is first solution:
df.loc[df.car=='RED BULL RACING HONDA', 'car'] = 'HONDA'
Upvotes: 2