31 Years of Python | 48 Hour Sale Extension!!!
days
hours
minutes
seconds

Replace empty string with an underscore

Screen Link: (Learn data science with Python and R projects)

My Code:

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

def tidy_columns(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 column in laptops.columns:
    new_columns.append(tidy_columns(column))
    
laptops.columns = new_columns

What I expected to happen:

What actually happened:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-cbdca536700a> in <module>
     15 
     16 for column in laptops.columns:
---> 17     new_columns.append(tidy_columns(column))
     18 
     19 laptops.columns = new_columns

<ipython-input-1-cbdca536700a> in tidy_columns(col)
      5     col = col.strip()
      6     col = col.replace('Operating System', 'os')
----> 7     col - col.replace(' ','_')
      8     col = col.replace('(','')
      9     col = col.replace(')','')

TypeError: unsupported operand type(s) for -: 'str' and 'str'

I couldn’t find a solution to the issue online. I will appreciate if anyone can help me with this problem.
Thanks

I did found the mistake in the code. I forgot my equal sign. :see_no_evil:

2 Likes