alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

[905] The replace() method in Pandas

In Pandas, the replace() method is used to replace values in a DataFrame or Series. You can use this method to replace one or more specified values with other values. Here's how you can use it:

Syntax:

DataFrame.replace(to_replace, value, inplace=False, limit=None, regex=False, method='pad')
  • to_replace: The value(s) you want to replace. This can be a single value, a list of values, or a dictionary that maps old values to new values.
  • value: The replacement value(s). This can be a single value or a list of values.
  • inplace: If set to True, the original DataFrame is modified in place, and no new DataFrame is returned. If set to False (the default), a new DataFrame with replacements is returned.
  • limit: An optional parameter that limits the number of replacements.
  • regex: If set to True, the to_replace parameter is treated as a regular expression.
  • method: Specifies how to handle replacements when limit is defined. By default, it's set to 'pad', which means forward fill.

Examples:

Here are some examples of how to use the replace() method:

  1. Replace a specific value in a Series:
import pandas as pd
data = pd.Series([1, 2, 3, 4, 5])
data.replace(2, 6, inplace=True)
print(data)

This will replace all occurrences of 2 with 6 in the Series.

  1. Replace multiple values in a DataFrame using a dictionary:
import pandas as pd
data = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [4, 3, 2, 1]})
replacement_dict = {'A': {1: 10, 3: 30}, 'B': {4: 40, 2: 20}}
data.replace(replacement_dict, inplace=True)
print(data)

In this example, you're replacing specific values in two columns of the DataFrame using a dictionary.

  1. Use regular expressions to replace values:
import pandas as pd
data = pd.Series(['apple', 'banana', 'cherry'])
data.replace(to_replace=r'^b\w+', value='fruit', regex=True, inplace=True)
print(data)

Here, you're using regular expressions to replace all words starting with 'b' with the word 'fruit'.

Keep in mind that when using replace() with inplace=True, the original data is modified, so use it with caution. If you're unsure about the results, you can also assign the result to a new variable without using inplace=True.

posted on   McDelfino  阅读(30)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2022-10-17 【753】Transformer模型
2020-10-17 【492】状态转移:初识马尔科夫链
2019-10-17 【443】Tweets Analysis Q&A
2016-10-17 【229】Raster Calculator - 栅格计算器
点击右上角即可分享
微信分享提示