1、常規(guī)操作
要從一個(gè) dataframe 中,篩選出某些列值符合要求的行數(shù)據(jù),可以用類似以下的語(yǔ)句實(shí)現(xiàn):
df[df[col] == x]
也可以用 .query() 實(shí)現(xiàn):
df.query('col == x')
2、其他操作方法
1)篩選出 col 列中值不是 bool 類型的行
df.query('col not in (True, False)')
2)篩選出 col 列中值為 nan、None 的值
df = pd.DataFrame({"value": [3,4,9,10,11,np.nan,12]})
# 方法1
# 利用 'nan 不等于自身' 的性質(zhì),篩選出非 nan、None 的行
df.query("value == value')
# 方法2
# 類似的還有 isnull, notnull,isnan 等
df.query('value.notna()', engine='python')
# 方法3
df.query('value != 'NaN'")
以上結(jié)果都是
Out[28]:
value
0 3.0
1 4.0
2 9.0
3 10.0
4 11.0
6 12.0
# 篩選出不是 NaT 的行(提前使用外部函數(shù),超綱了哈)
df.query('col not in [@pd.NaT]')
3)在 query 中篩選時(shí)引用外部變量
# 1. 外部為普通變量
# 方法1
pi = 3.1415
df.query('value < 10 and value > @pi')
# 方法2
pi = 3.1415
df.query(f'value < 10 and value > {pi}')
# 2.外部變量為 list
cond = [4, 12]
df.query('@cond[0] < value < @cond[1]')
# 3.外部變量為 dict,注意中括號(hào)中不能有引號(hào),因此要取 dict 的值,需要用 dict.get() 的方式
cond = {'dn_band': 4, 'up_band': 12}
df.query("@cond.get('dn_band') < value < @cond.get('up_band')")
# 4.外部為函數(shù)
num = [2, 6]
def func(x):
return x * 2
df.query('@func(@num[0]) < value < @func(@num[1])')
以上的結(jié)果都是
Out[30]:
value
3 10.0
4 11.0
參考資料:
1、Querying for NaN and other names in Pandas
2、DataFrame的assign和query方法