Curios About Replacement Function

col = col.replace("(","")

whats the function behind (" (?)
the story in data quest is not explain much yet

The code
import pandas as pd
laptops = pd.read_csv(‘laptops.csv’, encoding=‘Latin-1’)

def clean_col(col):
col = col.strip()
col = col.replace(“Operating System”, “os”)
col = col.replace(" “,”_“)
col = col.replace(”(“,”“)
col = col.replace(”)“,”")
col = col.lower()
return col

new_columns =
for c in laptops.columns:
clean_c = clean_col(c)
new_columns.append(clean_c)

laptops.columns = new_columns

the link

Hi!
I’m not sure if I understand your question properly.
Do you want to know more about the ‘replace’ function?

It works like this:
df = df.replace(‘old’, ‘new’)
It means:
In dataframe ‘df’, replace all occurences of ‘old’ with ‘new’, then assign the result back to ‘df’.

In the example you provided, you want to replace all occurences of ‘(’ with ‘’ in col. It deletes the left parenthesis and replaces it with nothing, so if for example you had: ‘(abc)’ you will get ‘abc)’.
In the following lines, you do the same with right parenthesis and replace blank spaces with ‘_’.

Here you can find documentation about replace: pandas.DataFrame.replace — pandas 1.4.4 documentation

Hope it is clearer now.

2 Likes