Pandas · Clean query text
Google Search Analytics
Course overviewGoogle Search · Prepare text and combine files

Clean query text

Normalize query whitespace and capitalization without overwriting the original text.

Step 1 of 3 · Learn

Trim the edges

Use .str.strip() to remove leading and trailing whitespace from every string in a Series. It leaves spaces inside the string unchanged. Create a new column so the original query stays available.

indextext
0 Blue Sky
1Red Fox
2NA
indextexttrimmed
0 Blue Sky Blue Sky
1Red FoxRed Fox
2NANA
Edge whitespace is removed; internal spacing and missing values stay unchanged.

Normalize case and repeated whitespace

Chain .str.lower() to lowercase text. .str.replace(r"\s+", " ", regex=True) collapses each run of whitespace into one space: \s means whitespace, and + means one or more. Use regex=False when replacing literal text.

indextext
0 Blue Sky
1RED FOX
2NA
indextextnormalized
0 Blue Sky blue sky
1RED FOXred fox
2NANA
Different casing and spacing become a consistent comparison value.

Keep missing and empty values distinct

These string methods preserve missing values. A whitespace-only string becomes "", not missing. Avoid .astype(str) here: it can turn missing values into literal text such as "None" or "<NA>". Cleaning text does not remove duplicate search events.

▷ Your turn

For every search, return search_id, query, and trimmed_query. Remove only leading and trailing whitespace in trimmed_query. Preserve query, internal whitespace, missing values, and source row order. Save the DataFrame as result.

LANGUAGEPython · Pandas

Loading Python and Pandas…

Run the code to see DataFrame results here.