← Back to Pandas Course | Chapter 5: Data Cleaning | Lesson 6 of 7

Values बदलना

replace एक पूरे Series या DataFrame में specific values को दूसरों से swap करता है।
Syntax
python
df["column"].replace(old_value, new_value)
df.replace({"old1": "new1", "old2": "new2"})

Values Replace करना

replace एक single value, एक list, या old values को नए में map करने वाला एक dict accept करता है। यह regex भी इस्तेमाल कर सकता है। यह categories recode करने या -999 जैसे placeholders को NaN में बदलने के लिए ideal है।

Note: -999 या "N/A" जैसी sentinel values को np.nan से replace करें ताकि Pandas इन्हें missing treat करे।

उदाहरण: Replacing values

python
import pandas as pd
import numpy as np

df = pd.DataFrame({"grade": ["A", "B", "N/A"], "score": [90, -999, 70]})
df = df.replace({"N/A": np.nan, -999: np.nan})
print(df)
print(df["grade"].replace({"A": "Excellent", "B": "Good"}))

# Output:
#   grade  score
# 0     A   90.0
# 1     B    NaN
# 2   NaN   70.0
# 0    Excellent
# 1         Good
# 2          NaN
# Name: grade, dtype: object
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. placeholders को NaN में convert न करना
  2. एक copy में replace करना और change खोना
  3. जब map ज़्यादा appropriate हो replace इस्तेमाल करना
चैप्टर सारांश
  • replace old को नई values में map करता है
  • dicts और lists accept करता है
  • Sentinel values के लिए great
  • Regex support करता है
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.