我认为您可以使用
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)
编辑:
对于多个mask
,可以使用以下方法:
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