深度阅读

How to replace values in pandas?

作者
作者
2023年08月22日
更新时间
16.33 分钟
阅读时间
0
阅读量

To replace values in pandas, you can use the replace() method on a pandas DataFrame or Series. Here are a few examples:

  1. Replace all occurrences of a specific value with another value:

import pandas as pd

create a sample dataframe

df = pd.DataFrame({‘A’: [1, 2, 3, 4], ‘B’: [‘a’, ‘b’, ‘a’, ‘d’]})

replace all occurrences of ‘a’ with ‘x’

df = df.replace(‘a’, ‘x’)

print(df)


This will output a new DataFrame with all occurrences of 'a' replaced with 'x':

A B
0 1 x
1 2 b
2 3 x
3 4 d


2. Replace all occurrences of multiple values with another value:

replace all occurrences of ‘a’ and ‘b’ with ‘x’

df = df.replace([‘a’, ‘b’], ‘x’)

print(df)


This will output a new DataFrame with all occurrences of 'a' and 'b' replaced with 'x':

A B
0 1 x
1 2 x
2 3 x
3 4 d


3. Replace values based on a dictionary:

replace all occurrences of {1: ‘one’, 2: ‘two’} in column ‘A’

df[‘A’] = df[‘A’].replace({1: ‘one’, 2: ‘two’})

print(df)


This will output a new DataFrame with all occurrences of 1 replaced with 'one' and all occurrences of 2 replaced with 'two' in column A:

 A  B

0 one a
1 two b
2 3 a
3 4 d



Note that the `replace()` method does not modify the DataFrame in place, rather it returns a new DataFrame with the replaced values. You need to assign the result of `replace()` back to the original DataFrame if you want to modify it in place.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。