df.rename(columns={'oldName1': 'newName1',
'oldName2': 'newName2'},
inplace=True, errors='raise')
# Make sure you set inplace to True if you want the change
# to be applied to the dataframe
#df.rename() will only return a new df with the new headers
#df = df.rename() will change the heders of the current dataframe
df = df.rename(columns={"old_col1": "new_col1", "old_col2": "new_col2"})
df_new = df.rename(columns={'A': 'a'}, index={'ONE': 'one'})
print(df_new)
# a B C
# one 11 12 13
# TWO 21 22 23
# THREE 31 32 33
print(df)
# A B C
# ONE 11 12 13
# TWO 21 22 23
# THREE 31 32 33
# Simple use case for pd.rename()
'''
old parameter = 'Data.Population'
new parameter = 'Population'
df.rename(columns={'old parameter': 'new parameter'}, inplace = True)
inplace = True : means to change object in real time
'''
# view below for visual aids
df.rename(columns={'Data.Population': 'Population'}, inplace = True)
# old columns
|'Data.Population'|
|_________________|
| 0 |
|_________________|
# new output:
# new rename column
|'Population' |
|_____________|
| 0 |
|_____________|
import pandas as pd
# You don't need these two lines
# as you already have your DataFrame in memory
df = pd.read_csv("nor.txt", sep="|")
df.drop(df.columns[-1], axis=1)
# Get column names
cols = df.columns
# Create a new DataFrame with just the markdown
# strings
df2 = pd.DataFrame([['---',]*len(cols)], columns=cols)
#Create a new concatenated DataFrame
df3 = pd.concat([df2, df])
#Save as markdown
df3.to_csv("nor.md", sep="|", index=False)