w3resource

Setting values with .loc in Pandas DataFrame


Pandas: Advanced Indexing and Slicing Exercise-11 with Solution


Setting Values with 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.

Python-Pandas Code Editor:

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

Previous: Conditional selection with .loc in Pandas DataFrame.
Next: Slicing DataFrame with .loc in Pandas.

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.