pandas按属性值筛选,isin

import pandas as pd
df = pd.DataFrame({'countries':['US','UK','Germany','China']})
df
Out[34]: 
  countries
0        US
1        UK
2   Germany
3     China

说明实例如上,有两种方式,第一种:

df1=df[df["countries"].isin(countries)]

df1
Out[28]: 
  countries
1        UK
3     China

df2=df[~df.countries.isin(countries)]
df2
Out[30]: 
  countries
0        US
2   Germany

第二种:

criterion = lambda row: row['countries'] not in countries

not_in = df[df.apply(criterion, axis=1)]

not_in
Out[33]: 
  countries
0        US

有一种情况用.isin会报错

criterion = lambda row: row['TOLLGATE_ID'] in gate_id_list and row["NEXT_TOLLGATE_ID"] in gate_id_list
test_df=test_df[test_df.apply(criterion,axis=1)]
 
#会报错    
test_df=test_df[test_df["TOLLGATE_ID"].isin(gate_id_list) and test_df["NEXT_TOLLGATE_ID"].isin(gate_id_list)]

并且row['TOLLGATE_ID',"NEXT_TOLLGATE_ID"] in gate_id_list 或者.isin

的写法不可以

参考:https://cloud.tencent.com/developer/ask/93371

 

 

你可能感兴趣的:(ML)