0
0
Data Analysis Pythondata~5 mins

replace() for value substitution in Data Analysis Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the replace() method do in pandas DataFrames?
The replace() method substitutes specified values in a DataFrame or Series with new values. It helps clean or modify data by changing unwanted or incorrect values.
Click to reveal answer
beginner
How do you replace all occurrences of the value 0 with 100 in a pandas DataFrame column named 'score'?
You can use: <br>df['score'] = df['score'].replace(0, 100)<br>This changes every 0 in 'score' to 100.
Click to reveal answer
intermediate
Can replace() handle multiple values at once? How?
Yes! You can pass a dictionary to replace() where keys are old values and values are new ones. For example:<br>df.replace({0: 100, -1: 999}) replaces 0 with 100 and -1 with 999 in the whole DataFrame.
Click to reveal answer
intermediate
What happens if you use replace() on a DataFrame without assigning it back or using inplace=True?
The original DataFrame stays the same because replace() returns a new DataFrame with changes. You must assign it back or use inplace=True to modify the original.
Click to reveal answer
beginner
Is it possible to replace values only in specific columns using replace()?
Yes. You can select columns first, then apply replace(). For example:<br>df['col1'] = df['col1'].replace(old, new) changes values only in 'col1'.
Click to reveal answer
What does df.replace(0, 100) do?
AReplaces 100 with 0
BReplaces all 0 values with 100 in the entire DataFrame
CAdds 100 to all 0 values
DDeletes all rows with 0
How do you replace multiple values at once in pandas?
AUsing a dictionary mapping old to new values
BUsing a list of values
CUsing a tuple of values
DUsing a string pattern
What must you do to keep changes after using replace()?
ANothing, changes are automatic
BCall <code>save()</code> method
CAssign the result back or use <code>inplace=True</code>
DRestart the kernel
Can replace() be used on a single column?
AOnly on string columns
BNo, only on entire DataFrames
COnly on numeric columns
DYes, by selecting the column first
Which of these is a correct way to replace -1 with NaN in pandas?
Adf.replace(-1, np.nan)
Bdf.replace(-1, None)
Cdf.replace(-1, 'NaN')
Ddf.replace(-1, 0)
Explain how to use replace() to change multiple values in a DataFrame.
Think about passing a map of old to new values.
You got /4 concepts.
    Describe what happens if you call replace() without assignment or inplace=True.
    Consider how pandas methods handle changes by default.
    You got /3 concepts.