
PYTHON — Modifying Values Accessor Methods in Python
Technology is best when it brings people together. — Matt Mullenweg

PYTHON — Python Walrus Operator Pitfalls
In this tutorial, we’ll explore how to modify values in dataframes using accessor methods in Python. We’ll use the pandas library to work with data efficiently.
Let’s start by understanding how to modify data in a dataframe using the .iloc and the .loc methods. We can modify parts of our dataframe by passing in a sequence, a NumPy array, or a single value.
Suppose we have a dataframe and we want to change the values in the py-score column for specific rows. We can achieve this by using the .loc method. For example, to change the py-score column for rows 0 to 13, we can use the following code:
# Change the py-score column for rows 0 to 13
df.loc[0:13, 'py-score'] = [40, 50, 60, 70]To set all the rows in the py-score column to 0, we can simply assign a single value of 0:
# Set all the rows in the py-score column to 0
df['py-score'] = 0We can also use the .iloc accessor method to modify specific rows or columns in the dataframe. For instance, to modify the last column using a NumPy array, we can use the following code:
import numpy as np
# Modify the last column using a NumPy array
df.iloc[:, -1] = np.linspace(20, 50, len(df))Additionally, we can modify individual cells of a dataframe using the .loc method. For example, to change the city for the row labeled 11, we can do the following:
# Change the city for the row labeled 11
df.loc[11, 'city'] = 'Ottawa'As you can see, modifying values in pandas dataframes is similar to accessing and modifying values in NumPy arrays.
That’s it for modifying values in dataframes using accessor methods in Python. In the next tutorial, we’ll discuss inserting and deleting data from a pandas dataframe.







