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

[pandas tip] add a new column

編輯:Python
Enjoy the beautiful picture 2022/06/18

Data preparation

import pandas as pd
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])

df


In normal development , Adding new data columns involves the following three common methods :

1.  Direct assignment

grammar : df[ New column names ] = value

import pandas as pd
import numpy as np
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
# Add null data column
# add to 'Level','Remark' Column , Set the values of the two columns to null (keep blank)
df['Level'] = np.nan
df['Remark'] = np.nan

2.reindex() function

grammar : df.reindex(columns=[ All original column names , New column name ],fill_value= value )

import pandas as pd
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
# Add new column 'Quantity' and 'Product_number', And set its value to 0
df = df.reindex(columns = ['Site', 'Quantity', 'Product_number'], fill_value=0)

Be careful :  No addition fill_value Parameters , The default value is nan

3.loc() function

grammar : df.loc[:, New column names ] = value

import pandas as pd
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
# Add new column 'Description', And set its value to 'Good'
df.loc[:,'Description'] = 'Good'


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