w3resource

Setting values with .loc in Pandas DataFrame


11. Setting Values Using .loc

Write a Pandas program that uses .loc to set values in the DataFrame.

Sample Solution :

Python Code :

import pandas as pd

# Create a DataFrame
df = pd.DataFrame({
    'X': [1, 6, 8, 3, 7],
    'Y': [5, 2, 9, 4, 1]
})

# Set values using .loc
df.loc[df['X'] > 5, 'Y'] = 0
print(df)

Output:

   X  Y
0  1  5
1  6  0
2  8  0
3  3  4
4  7  0

Explanation:

  • Import pandas library.
  • Create a DataFrame.
  • Use .loc to set values in column 'Y' where column 'X' > 5.
  • Print the DataFrame.

For more Practice: Solve these Related Problems:

  • Write a Pandas program to use .loc to update specific values in a DataFrame and then display the modified DataFrame.
  • Write a Pandas program to set new values in a DataFrame column for rows that meet a condition using .loc.
  • Write a Pandas program to modify a DataFrame by assigning a constant value to a subset of rows using .loc and verify the change.
  • Write a Pandas program to use .loc to set values in multiple columns simultaneously for rows meeting a given condition.

Go to:


PREV : .loc Row Selection Based on Condition.
NEXT : .loc Slicing Based on Row and Column Labels.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.