insert(loc, column, value, allow_duplicates=False)
在哪里:
loc: 插入列的索引。第一列是 0。
column: 赋予新列的名称。
value: 新列的值数组。
allow_duplicates: 是否允许新列名匹配现有列名。默认值为假。
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
#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
#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