數據准備
import pandas as pd
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
df
在平時開發中,添加新數據列涉及到以下三種常用方法:
1. 直接賦值
語法: df[新列名] = 值
import pandas as pd
import numpy as np
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
# 添加空值數據列
# 添加'Level','Remark'列,將兩列的值設置為空(keep blank)
df['Level'] = np.nan
df['Remark'] = np.nan
2.reindex()函數
語法: df.reindex(columns=[原來所有的列名,新增列名],fill_value=值)
import pandas as pd
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
# 添加新列'Quantity'和'Product_number',並將其值設置為0
df = df.reindex(columns = ['Site', 'Quantity', 'Product_number'], fill_value=0)
注意: 不加fill_value參數,默認值為nan
3.loc()函數
語法: df.loc[:,新列名] = 值
import pandas as pd
df = pd.DataFrame([['ABC'],
['FJZ'],
['FOC']
],columns=['Site'])
# 添加新列'Description',並將其值設置為'Good'
df.loc[:,'Description'] = 'Good'