0
0
Pandasdata~5 mins

str.replace() for substitution in Pandas - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does str.replace() do in pandas?

str.replace() substitutes parts of strings in a pandas Series or DataFrame column with another string.

Click to reveal answer
beginner
How do you replace all occurrences of 'cat' with 'dog' in a pandas Series named pets?
pets.str.replace('cat', 'dog')
Click to reveal answer
intermediate
What parameter do you use in str.replace() to treat the pattern as a regular expression?

The regex parameter. By default, it is True, meaning the pattern is treated as a regex.

Click to reveal answer
intermediate
How can you replace only the first occurrence of a pattern in each string using str.replace()?

Use the n=1 parameter to limit replacement to the first match.

Click to reveal answer
intermediate
What happens if you set regex=False in str.replace()?

The pattern is treated as a literal string, not a regular expression.

Click to reveal answer
What is the default behavior of the pattern parameter in str.replace()?
AIt replaces only the first occurrence
BIt treats the pattern as a literal string
CIt ignores the pattern
DIt treats the pattern as a regular expression
How do you replace all occurrences of 'apple' with 'orange' in a pandas Series fruits?
Afruits.replace('apple', 'orange')
Bfruits.str.sub('apple', 'orange')
Cfruits.str.replace('apple', 'orange')
Dfruits.str.change('apple', 'orange')
Which parameter limits the number of replacements in str.replace()?
Alimit
Bn
Ccount
Dmax
If you want to replace the literal string '.' (dot), what should you do?
AEscape the dot or set <code>regex=False</code>
BUse <code>case=False</code>
CUse <code>n=0</code>
DUse <code>regex=True</code>
What type of object does str.replace() return when used on a pandas Series?
AA pandas Series
BA numpy array
CA list
DA string
Explain how to use str.replace() in pandas to substitute text in a Series. Include how to handle regular expressions and limit replacements.
Think about how you change words in a list of sentences.
You got /4 concepts.
    Describe a real-life example where str.replace() in pandas can help clean data.
    Imagine fixing a messy list of names or addresses.
    You got /4 concepts.