Access and Modify DataFrames Values
Let's find out how to access and modify pandas DataFrame values.
We'll cover the following
Try it yourself
Try executing the code below to see the result.
import pandas as pddf = pd.DataFrame([['Bugs', True, 72.3],['Daffy', False, 30.7],['Tweety', True, 23.5],['Elmer', False, 103.9],], columns=['Customer', 'Member', 'Amount'])df[df['Member']]['Amount'] *= 0.9print(df)
Explanation
The change is not reflected in df
. The reason is that pandas does a lot of work
under the hood to avoid copying data. However, in some cases, it can’t. In those cases, we get a copy of the data.
The warning is helpful. Unfortunately, lots of developers ignore it.
discount.py:11: SettingWithCopyWarning:
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
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs...
The existence of the warning above indicates that many developers face this same issue. Let’s apply the warning suggestion to our code:
Solution
import pandas as pddf = pd.DataFrame([['Bugs', True, 72.3],['Daffy', False, 30.7],['Tweety', True, 23.5],['Elmer', False, 103.9],], columns=['Customer', 'Member', 'Amount'])df.loc[df['Member'], 'Amount'] *= 0.9print(df)
Get hands-on with 1300+ tech skills courses.