如何在不返回 False 值的情况下从 pandas df 中获取 select 行?
how do I select rows from pandas df without returning False values?
我有一个 df,我需要根据多列中的某些条件 select 行。
这是我的
import pandas as pd
dat = [('p','q', 5), ('k','j', 2), ('p','-', 5), ('-','p', 4), ('q','pkjq', 3), ('pkjq','q', 2)
df = pd.DataFrame(dat, columns = ['a', 'b', 'c'])
df_dat = df[(df[['a','b']].isin(['k','p','q','j']) & df['c'] > 3)] | df[(~df[['a','b']].isin(['k','p','q','j']) & df['c'] > 2 )]
预期结果= [('p','q', 5), ('p','-', 5), ('-','p', 4), ('q','pkjq', 3)]
我得到的结果是一个完全错误的数据帧
当你有我推荐的复杂条件时,将条件放在切片之外
cond1 = df[['a','b']].isin(['k','p','q','j']).any(1) & df['c'].gt(3)
cond2 = (~df[['a','b']].isin(['k','p','q','j'])).any(1) & df['c'].gt(2)
out = df.loc[cond1 | cond2]
Out[305]:
a b c
0 p q 5
2 p - 5
3 - p 4
4 q pkjq 3
我有一个 df,我需要根据多列中的某些条件 select 行。
这是我的
import pandas as pd
dat = [('p','q', 5), ('k','j', 2), ('p','-', 5), ('-','p', 4), ('q','pkjq', 3), ('pkjq','q', 2)
df = pd.DataFrame(dat, columns = ['a', 'b', 'c'])
df_dat = df[(df[['a','b']].isin(['k','p','q','j']) & df['c'] > 3)] | df[(~df[['a','b']].isin(['k','p','q','j']) & df['c'] > 2 )]
预期结果= [('p','q', 5), ('p','-', 5), ('-','p', 4), ('q','pkjq', 3)]
我得到的结果是一个完全错误的数据帧
当你有我推荐的复杂条件时,将条件放在切片之外
cond1 = df[['a','b']].isin(['k','p','q','j']).any(1) & df['c'].gt(3)
cond2 = (~df[['a','b']].isin(['k','p','q','j'])).any(1) & df['c'].gt(2)
out = df.loc[cond1 | cond2]
Out[305]:
a b c
0 p q 5
2 p - 5
3 - p 4
4 q pkjq 3