在使用df的loc布尔索引时,其实里面的列可以是原来列表中没有存在的。。。
import pandas as pd import numpy as np boolean=[True,False] gender=[‘男‘,‘女‘] color=[‘green‘,‘blue‘,‘yellow‘] data=pd.DataFrame({‘height‘:np.random.randint(150,190,100), ‘weight‘:np.random.randint(40,90,100), ‘smoker‘:[boolean[x] for x in np.random.randint(0,2,100)], ‘gender‘:[gender[x] for x in np.random.randint(0,2,100)], ‘age‘:np.random.randint(15,90,100), ‘color‘:[color[x] for x in np.random.randint(0,len(color),100)]}) data.loc[data[‘gender‘]==‘男‘,‘xingbie‘]=1 #里面的xingbie 的列原来并没有存在
原先使用的还以为是语法错误
原文:https://www.cnblogs.com/cgmcoding/p/13905941.html