How to change one value based on another value in Python pandas?

Estimated read time 1 min read

To change one value based on another value in Python using the pandas library, you can use conditional statements and the DataFrame indexing capabilities. Here’s an example:

import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({'A': [10, 20, 30, 40],
                   'B': [50, 60, 70, 80]})

# Display the original DataFrame
print("Original DataFrame:")
print(df)

# Change the value in column 'B' based on a condition in column 'A'
df.loc[df['A'] > 20, 'B'] = 100

# Display the updated DataFrame
print("\nUpdated DataFrame:")
print(df)

Output:

Original DataFrame:
    A   B
0  10  50
1  20  60
2  30  70
3  40  80

Updated DataFrame:
    A    B
0  10   50
1  20   60
2  30  100
3  40  100

In this example, we have a DataFrame df with columns ‘A’ and ‘B’. We want to change the values in column ‘B’ based on a condition in column ‘A’.

The line df.loc[df['A'] > 20, 'B'] = 100 selects the rows where the values in column ‘A’ are greater than 20 and sets the corresponding values in column ‘B’ to 100.

You can modify the condition and the value assignment based on your specific requirements. The df.loc indexing method allows you to select specific rows and columns based on conditions, and then assign a new value to those selected cells.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply