Usually , You may wish to be in Pandas DataFrame Insert a new column . Fortunately, , Use pandasinsert() Functions can easily do this , This function uses the following syntax :
insert(loc, column, value, allow_duplicates=False)
Where is the :
This tutorial shows several examples of how to use this feature in practice .
The following code shows how to insert a new column as an existing DataFrame The first column :
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
'assists': [5, 7, 7, 9, 12],
'rebounds': [11, 8, 10, 6, 6]})
#view DataFrame
df
points assists rebounds
0 25 5 11
1 12 7 8
2 15 7 10
3 14 9 6
4 19 12 6
#insert new column 'player' as first column
player_vals = ['A', 'B', 'C', 'D', 'E']
df.insert(loc=0, column='player', value=player_vals)
df
player points assists rebounds
0 A 25 5 11
1 B 12 7 8
2 C 15 7 10
3 D 14 9 6
4 E 19 12 6
The following code shows how to insert a new column as an existing DataFrame The third column of :
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
'assists': [5, 7, 7, 9, 12],
'rebounds': [11, 8, 10, 6, 6]})
#insert new column 'player' as third column
player_vals = ['A', 'B', 'C', 'D', 'E']
df.insert(loc=2, column='player', value=player_vals)
df
points assists player rebounds
0 25 5 A 11
1 12 7 B 8
2 15 7 C 10
3 14 9 D 6
4 19 12 E 6
The following code shows how to insert a new column as an existing DataFrame The last column of :
import pandas as pd
#create DataFrame
df = pd.DataFrame({'points': [25, 12, 15, 14, 19],
'assists': [5, 7, 7, 9, 12],
'rebounds': [11, 8, 10, 6, 6]})
#insert new column 'player' as last column
player_vals = ['A', 'B', 'C', 'D', 'E']
df.insert(loc=len(df.columns), column='player', value=player_vals)
df
points assists player rebounds
0 25 5 A 11
1 12 7 B 8
2 15 7 C 10
3 14 9 D 6
4 19 12 E 6
Please note that , Use **len(df.columns)** Allows you to insert a new column as the last column in any data frame , No matter how many columns it may have .
You can go to here find insert() Complete documentation of functions .