1.使用pd.loc
import pandas as pd
data=[['mark',55,'Italy',4.5,'Europe'],
['John',33,'China',3.8,'Asian'],
['mary',40,'Japan',2.3,'Asian']]
df=pd.DataFrame(data=data,columns=['name','age','country','score','continent'],
index=[1001,1002,1003])
df1=df.copy()
df.loc[df1['name']=='mary','country']= 'korea'
print(df)
2.使用pd.iloc
import pandas as pd
data=[['mark',55,'Italy',4.5,'Europe'],
['John',33,'China',3.8,'Asian'],
['mary',40,'Japan',2.3,'Asian']]
df=pd.DataFrame(data=data,columns=['name','age','country','score','continent'],
index=[1001,1002,1003])
cri=(df['name']=='mary')|(df['name']=='John')
df.iloc[cri,2]='Korea'
print(df)
import pandas as pd
data=[['mark',55,'Italy',4.5,'Europe'],
['John',33,'China',3.8,'Asian'],
['mary',40,'Japan',2.3,'Asian']]
df=pd.DataFrame(data=data,columns=['name','age','country','score','continent'],
index=[1001,1002,1003])
df=df.replace('Asian','America')
print(df)
注:同样
pd.replace不对原Dataframe做改变,需要重新对Dataframe赋值
4. 添加新列
import pandas as pd
import numpy as np
data=[['mark',55,'Italy',4.5,'Europe'],
['John',33,'China',3.8,'Asian'],
['mary',40,'Japan',2.3,'Asian']]
df=pd.DataFrame(data=data,columns=['name','age','country','score','continent'],
index=[1001,1002,1003])
df.loc[:,'discount']=np.arange(1,4)
df.insert(2,'starts','none')
print(df)