程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to insert a column in pandas dataframe

編輯:Python

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 :

  • **loc:** Insert the index of the column . The first column is 0.
  • **column:** Give the new column a name .
  • value**:** Array of values for the new column .
  • **allow_duplicates:** Whether to allow new column names to match existing column names . The default is false .

This tutorial shows several examples of how to use this feature in practice .

Example 1: Insert a new column as the first column

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

Example 2: Insert new column as middle column

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

Example 3: Insert new column as last column

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 .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved