我认为您可以将numpy.where 与between 创建的布尔掩码一起使用并与city 进行比较:
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000)
df['status'] = np.where(mask, 'Correct', 'Uncorrect')
示例:
df = pd.DataFrame({'city':['mumbai','mumbai','mumbai', 'a'],
'rent':[1000,6000,10000,10000]})
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000)
df['status'] = np.where(mask, 'Correct', 'Flag')
print (df)
city rent status
0 mumbai 1000 Flag
1 mumbai 6000 Correct
2 mumbai 10000 Correct
3 a 10000 Flag
loc 的另一种解决方案:
mask = (df['city']=='mumbai') & df['rent'].between(5000,15000)
df['status'] = 'Flag'
df.loc[mask, 'status'] = 'Correct'
print (df)
city rent status
0 mumbai 1000 Flag
1 mumbai 6000 Correct
2 mumbai 10000 Correct
3 a 10000 Flag
写入excel使用to_excel,如果需要删除索引列添加index=False:
df.to_excel('file.xlsx', index=False)
编辑:
对于多个masks 可以使用:
df = pd.DataFrame({'city':['Mumbai','Mumbai','Delhi', 'Delhi', 'Bangalore', 'Bangalore'],
'rent':[1000,6000,10000,1000,4000,5000]})
print (df)
city rent
0 Mumbai 1000
1 Mumbai 6000
2 Delhi 10000
3 Delhi 1000
4 Bangalore 4000
5 Bangalore 5000
m1 = (df['city']=='Mumbai') & df['rent'].between(5000,15000)
m2 = (df['city']=='Delhi') & df['rent'].between(1000,5000)
m3 = (df['city']=='Bangalore') & df['rent'].between(3000,5000)
m = m1 | m2 | m3
print (m)
0 False
1 True
2 False
3 True
4 True
5 True
dtype: bool
from functools import reduce
mList = [m1,m2,m3]
m = reduce(lambda x,y: x | y, mList)
print (m)
0 False
1 True
2 False
3 True
4 True
5 True
dtype: bool
print (df[m])
city rent
1 Mumbai 6000
3 Delhi 1000
4 Bangalore 4000
5 Bangalore 5000