2 回答
TA贡献1859条经验 获得超6个赞
Alt1:
您可以使用两个遮罩(条件)来完成此操作。这应该是可读且有意义的。
m1 = (df.gender == 'male')
m2 = (df.gender.duplicated())
df.loc[m1&m2, 'score'] = 0
Alt2:
切掉非零掩码的第一个真值(需要import numpy as np)。这应该更快。
m = np.nonzero(df.gender=='male')[0][1:]
df.loc[m, 'score'] = 0
完整示例:
import pandas as pd
import numpy as np
df = pd.DataFrame({
'gender': ['male','female','male','female','male'],
'score': 34
})
m1 = (df.gender == 'male')
m2 = (df.gender.duplicated())
m = np.nonzero(df.gender=='male')[0][1:]
df.loc[m, 'score'] = 0
print(df)
返回值:
gender score
0 male 34
1 female 34
2 male 0
3 female 34
4 male 0
TA贡献1876条经验 获得超6个赞
我觉得你需要
m=df.loc[2:5,:].loc[df['gender']=='male']
df.loc[m.index,'score']=0
print(df)
gender score
0 male 34
1 female 34
2 male 0
3 female 34
4 male 0
添加回答
举报