![](/img/trans.png)
[英]How can I extract values from a dataframe or filter based on some criteria in Python?
[英]How to create filter condition from dataframe based on some criteria?
我需要根據 dataframe 中的某些條件創建過濾條件。我卡在這里了。 你能幫我解決我的問題嗎? 提前致謝!
例子:
Df:
0 1
0 kol_id 101152
1 jnj_id 7124166
2 thrc_cd VIR
3 operator <=
4 start_dt 05/10/2018
使用上面的 dataframe 我需要創建以下過濾器查詢:
kol_id = '101152' and jnj_id = '7124166' and thrc_cd = 'VIR' and start_dt <= '05/10/2018'
如果運算符將出現在任何行中,則意味着該運算符值將在下一行過濾條件中使用,否則只有“=”運算符將在所有過濾條件中使用。
您可以在 pandas 中使用掩碼和移位:
假設您有以下內容:
df = pd.DataFrame({'col1': ['kol', 'jnj', 'thrc', 'operator', 'start'], 'col2': [100, 200, 'VIR', '<=', '05/10/2018']})
In [10]: df
Out[10]:
col1 col2
0 kol 100
1 jnj 200
2 thrc VIR
3 operator <=
4 start 05/10/2018
當您屏蔽col1
不是operator
的每一行時,然后向底部移動然后填充您得到的默認運算符:
df['operator'] = df.mask(df['col1']!='operator').shift()['col2'].fillna('==')
In [14]: df
Out[14]:
col1 col2 shifted
0 kol 100 ==
1 jnj 200 ==
2 thrc VIR ==
3 operator <= ==
4 start 05/10/2018 <=
現在您可以刪除 col1 中包含operator
的行。
並連接列以獲得您的條件:
In [17]: df['res'] = '(' + df['col1'] + df.shifted + df['col2'].astype(str) + ')'
In [18]: df
Out[18]:
col1 col2 shifted res
0 kol 100 == (kol==100)
1 jnj 200 == (jnj==200)
2 thrc VIR == (thrc==VIR)
3 start 05/10/2018 <= (start<=05/10/2018)
最后加入你的列res
來獲取你的條件
In [19]: ' and '.join(df.res)
Out[19]: '(kol==100) and (jnj==200) and (thrc==VIR) and (start<=05/10/2018)'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.