Changing column names from dataframe

Question:

I have a dataframe with all the companies listed in the S&P500 with their daily data. However in each dataframe column name there is an undesired "/n" appended to it and I want to remove it.

I get the following error:

df.columns = df.columns.str.replace('*.n.*', '')
  File "C:Python37libsite-packagespandascorestrings.py", line 1843, in wrapper
    return func(self, *args, **kwargs)
  File "C:Python37libsite-packagespandascorestrings.py", line 2716, in replace
    self._parent, pat, repl, n=n, case=case, flags=flags, regex=regex
  File "C:Python37libsite-packagespandascorestrings.py", line 619, in str_replace
    compiled = re.compile(pat, flags=flags)
  File "C:Python37libre.py", line 234, in compile
    return _compile(pattern, flags)
  File "C:Python37libre.py", line 286, in _compile
    p = sre_compile.compile(pattern, flags)
  File "C:Python37libsre_compile.py", line 764, in compile
    p = sre_parse.parse(p, flags)
  File "C:Python37libsre_parse.py", line 930, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "C:Python37libsre_parse.py", line 426, in _parse_sub
    not nested and not items))
  File "C:Python37libsre_parse.py", line 651, in _parse
    source.tell() - here + len(this))
re.error: nothing to repeat at position 0 (line 1, column 1)

This is the function causing the error:

def remove_extra_characters(df):
    df.columns = df.columns.str.replace('*.n.*', '')
Asked By: Giulio DiZio

||

Answers:

Here you go! New-lines be gone! 🙂

import pandas as pd

data = [['tom', 10], ['nick', 15], ['juli', 14]]

df = pd.DataFrame(data, columns=['Namennn', 'Agenn'])

df.rename(columns={old:old.strip() for old in df.columns}, inplace=True)

print(df)
Answered By: Toothpick Anemone
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.