匹配列表元素与数据框元素python

时间:2018-12-05 20:16:14

标签: python regex pandas list dataframe

我有一些类似如下的列表:

l1 = ['Category=worker,manager','Name=Ana,Tom', 'Task=Cleaning,Plumbing']

然后我有了数据框df:

Name    | Category        | Task       | OrderNum

Bryan   | worker,manager  | Cleaning,Plumbing | 2
Ana,Tom | worker,manager  | Cleaning,Plumbing | 3

我想找到一个列表项,在相应的df列中找到匹配的值,找到列表的所有匹配项后,再从OrderNum列中返回其值。

我该怎么办?

1 个答案:

答案 0 :(得分:2)

给出:

>>> l1 = ['Category=worker,manager','Name=Ana,Tom', 'Task=Cleaning,Plumbing']
>>> 
>>> df
      Name        Category               Task  OrderNum
0    Bryan  worker,manager  Cleaning,Plumbing         2
1  Ana,Tom  worker,manager  Cleaning,Plumbing         3

您可以像这样从l1进行查询:

>>> query = ' and '.join("{} == '{}'".format(*s.split('=')) for s in l1)
>>> query
"Category == 'worker,manager' and Name == 'Ana,Tom' and Task == 'Cleaning,Plumbing'"

...然后发出

>>> df.query(query)
      Name        Category               Task  OrderNum
1  Ana,Tom  worker,manager  Cleaning,Plumbing         3

>>> df.query(query)['OrderNum']
1    3
Name: OrderNum, dtype: int64

>>> result, = df.query(query)['OrderNum']
>>> result
3

如果您希望恰好是一击,或者

>>> result = df.query(query)['OrderNum'].iat[0]
>>> result
3

如果您希望至少有一个匹配项,并且想将result分配给第一个匹配项,则不管有多少个匹配项。