learn2learn
learn2learn

Reputation: 11

pandas: capitalize all or the first n words in the column names

I am trying to find how to capitalize the first and second word of column header.

Example:

check match ==> Check Match

date found ==> Date Found

Thank you

Upvotes: 0

Views: 3081

Answers (3)

mozway
mozway

Reputation: 260640

capitalize all words

If you want to capitalize all words, use:

df.columns = df.columns.str.title()

or:

df.rename(columns=str.title, inplace=True)

Example:

df = pd.DataFrame(columns=['example', 'longer example', 'quite longer example'])

output headers:

['Example', 'Longer Example', 'Quite Longer Example']

capitalize only the first n words

df.columns = df.columns.str.replace(r'(\w+)', lambda x: x.group().capitalize(),
                                    n=2, regex=True)

example:

['Example', 'Longer Example', 'Quite Longer example']

Upvotes: 6

guardian
guardian

Reputation: 311

Did you try?

df.columns=df.columns.str.title()

Upvotes: 0

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 9865

# if your data frame is `df`, then:
df.columns = [s.capitalize() for s in df.columns]

Upvotes: 1

Related Questions