[896] Replace values in a DataFrame

发布时间 2023-10-10 08:44:57作者: McDelfino

You can replace values in a Pandas DataFrame using the replace() method or by directly assigning new values to specific DataFrame elements. Here's how to do both:

Using replace() Method:

The replace() method allows you to replace specific values with new values throughout the DataFrame. You can specify the values to be replaced and their corresponding replacement values.

import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': ['apple', 'banana', 'cherry', 'date', 'elderberry']}

df = pd.DataFrame(data)

# Replace specific values in column 'A'
df['A'] = df['A'].replace({2: 20, 4: 40})

# Replace specific values in column 'B'
df['B'] = df['B'].replace({'banana': 'pear', 'cherry': 'grape'})

print(df)

In this example, we replaced the values 2 with 20 and 4 with 40 in column 'A', and 'banana' with 'pear' and 'cherry' with 'grape' in column 'B'.

Direct Assignment:

You can also directly assign new values to specific DataFrame elements using indexing.

import pandas as pd

# Create a sample DataFrame
data = {'A': [1, 2, 3, 4, 5],
        'B': ['apple', 'banana', 'cherry', 'date', 'elderberry']}

df = pd.DataFrame(data)

# Replace values using direct assignment
df['A'][df['A'] == 2] = 20
df['A'][df['A'] == 4] = 40
df['B'][df['B'] == 'banana'] = 'pear'
df['B'][df['B'] == 'cherry'] = 'grape'

print(df)

In this example, we directly replaced values using conditional indexing.

Both methods will yield the same result, and you can choose the one that best suits your needs and coding style.