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'