[英]Function to match columns and values to rows - intersection of DataFrames
可以說我有以下DataFrame:
>>>df = pd.DataFrame([[5,2,3,11],[5,3,3,8],[9,4,11,12],[5,14,15,16]],columns=["a","b","c","d"])
>>>df
a b c d
0 5 2 3 11
1 5 3 3 8
2 9 4 11 12
3 5 14 15 16
如果我想匹配所有具有列值的行:'a'等於5,'b'<10並且'c'大於或等於3,我可以執行以下操作:
df[(df['a'] == 5) & (df['b'] < 10) & (df['c'] >= 3)]
這會給我帶來我想要的結果:
a b c d
0 5 2 3 11
1 5 3 3 8
輸入該代碼以匹配行很費力,因此我決定制作一個名為row_matcher
的函數,該函數需要2個參數:Pandas DataFrame和長度為3的列表列表-選擇,運算符和值的列。
def get_operator_fn(op):
import operator
return {
'<' : operator.lt,
'<=' : operator.le,
'==' : operator.eq,
'!=' : operator.ne,
'>=' : operator.ge,
'>' : operator.gt,
'&' : operator.and_
}[op]
def row_matcher(df,parameters):
import pandas as pd
"""Parameter should be [column,operation,value]
Example: ['trial',"==",1]
"""
operations = [df[get_operator_fn(operation)(df[column],value)] for column,operation,value in parameters]
return reduce(lambda left,right: pd.merge(left,right,how='inner'), operations)
>>>row_matcher(df,[["a","==",5],["b","<",10],["c",">=",3]])
不幸的是,使用此代碼,它為return reduce(...)
行引發了錯誤: TypeError: Could not compare <type 'str'> type with Series
我試圖用df[reduce(operator.and_,operations)]
代替return reduce(...)
行。
這仍然會導致錯誤: TypeError: unsupported operand type(s) for &: 'str' and 'str'
我將不勝感激。
我認為使用query()方法會簡單得多。 使用此示例,您的初始示例可以寫為:
df.query('a==5 & b<10 & c>=3')
老實說,如果您使用query()方法,除非您要從外部文件中讀取許多條件,否則我認為您不會從函數中獲得太多收益。 如果仍要編寫row_matcher
函數,則只需使用字符串連接,就可以使用query()語法將列表列表組合為單個字符串。 擁有單個字符串后,將其傳遞給query()方法。
您可能需要安裝numexpr
模塊才能使用query()方法。 您可以通過向query()方法提供關鍵字參數engine='python'
來解決此問題。 這可能不如使用numexpr
模塊有效,因此,如果性能成為問題,則可能值得安裝該模塊。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.