how to rename multiple columns in pandas code example
Example 1: python how to rename columns in pandas dataframe
pandas_dataframe.columns = ['list', 'of', 'column', 'names']
pandas_dataframe.rename(columns={'column_name_to_change':'new_name'})
pandas_dataframe.index = ['list', 'of', 'row', 'names']
pandas_dataframe.rename(index={'row_name_to_change':'new_name'})
Example 2: rename multiple pandas columns with list
for j in range(len(df.columns)):
old = df.columns[j]
new = new_columns[j]
df = df.rename(columns = {old:new})
Example 3: python add multiple columns to pandas dataframe
df[['new_column_1_name', 'new_column_2_name']] = pd.DataFrame([[np.nan, 'word']], index=df.index)
import pandas as pd
import numpy as np
df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
print(df)
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
df[['new_col_1', 'new_col_2', 'new_col_3']] = pd.DataFrame([[np.nan, 42, 'wow']], index=df.index)
print(df)
col_1 col_2 new_col_1 new_col_2 new_col_3
0 0 4 NaN 42 wow
1 1 5 NaN 42 wow
2 2 6 NaN 42 wow
3 3 7 NaN 42 wow
df['new_col_1'] = np.nan
df['new_col_2'] = 42
df['new_col_3'] = 'wow'