How can i use method chaining to single-line the entire cleaning operation

Screen Link:

https://app.dataquest.io/c/54/m/293/data-cleaning-basics/3/cleaning-column-names-continued

My Code:
My obviously futile attempt at chaining methods for combining all operations at once in replace and clean to put it up in single line.

import pandas as pd
laptops = pd.read_csv('laptops.csv', encoding='Latin-1')

def string_cleaner(str1):
    cln_str1 = str1.replace("Operating System", "os").strip().lower().replace(" ", "-").replace(("("or")"),'')
    return cln_str1

clean_columns = []
for col in laptops.columns:
    clean_columns.append(string_cleaner(col))
laptops.column = clean_columns

What I expected to happen:
Refer to screenshot

What actually happened:
Refer to screenshot

Refer to screenshot


also incase the link above dont work here it is pasted again
https://app.dataquest.io/c/54/m/293/data-cleaning-basics/3/cleaning-column-names-continued

My main question is, what is the correct order of chaining methods. And if at all can we chain this entire set of operations together?

Thankyou

let me know if any1 can help

@neo.vandamme1 If I were to guess, probably to deal with brackets (as you can see the syntax highlighting for or is off). Also, the brackets should be replaced separately, not using an or (this is not defined in the documentation for .replace().

A few other errors a spotted the replacement of space ( " ") should be with underscore ( "_"), not dash ( "-"). Also you mispelt the property to be assigned (it should be
laptops.columns not laptops.column).

Here’s a successful alternative if you still require multiple chaining (which I do not recommend as in might confuse you - which it likely did in this case).

import pandas as pd
laptops = pd.read_csv('laptops.csv', encoding='Latin-1')

def string_cleaner(str1):
    cln_str1 = str1.replace("Operating System", "os").strip().lower().replace(" ", "_").replace("(","").replace(")","")
    return cln_str1

clean_columns = []
for col in laptops.columns:
    clean_columns.append(string_cleaner(col))
laptops.columns = clean_columns
1 Like

Thankyou, i guess my keyboard is getting sick of me. I will try those corrections and give it a shot if it works

1 Like