简体   繁体   English

检查 pandas 列值是否在另一列的列表中

[英]Check if pandas column value is inside another column's list

I have a pandas column like this where amount is a string column:我有一个像这样的 pandas 列,其中 amount 是一个字符串列:

id      amount    possible_amount
0        1.00       ['1.00', '2.00', '3.00']
1       45.00       ['100.00', '45.00']
2       37.00       ['29.00', '38.00']

I want to create a new column called 'match' whose value will be True if amount is in the possible_amount list and False otherwise.我想创建一个名为“match”的新列,如果amountpossible_amount列表中,则其值为True ,否则为False So expected results for example above is:所以上面例子的预期结果是:

id      amount    possible_amount                     match
0        1.00       ['1.00', '2.00', '3.00']           True
1       45.00       ['100.00', '45.00']                True
2       37.00       ['29.00', '38.00']                 False

I've tried couple different ways, below being one of them.我尝试了几种不同的方法,以下是其中之一。 Also tried using str.contains() to no avail.还尝试使用str.contains()无济于事。

df['match'] = np.where(df['amount'].isin(df['possible_amount']), True, False)

But this only returns all False in match .但这只会返回match的所有 False 。

Convert values to floats and compare in list comprehension:将值转换为浮点数并在列表理解中进行比较:

df['match'] = [a in list(map(float, b)) for a, b in zip(df['amount'],df['possible_amount'])]
print (df)
   id  amount     possible_amount  match
0   0     1.0  [1.00, 2.00, 3.00]   True
1   1    45.0     [100.00, 45.00]   True
2   2    37.0      [29.00, 38.00]  False

Another idea, obviously slowier:另一个想法,显然更慢:

df['match'] = (df.explode('possible_amount')
                 .assign(possible_amount = lambda x: x['possible_amount'].astype(float),
                         new = lambda x: x['possible_amount'].eq(x['amount']))
                 .groupby(level=0)['new']
                 .any()
         )

print (df)
   id  amount     possible_amount  match
0   0     1.0  [1.00, 2.00, 3.00]   True
1   1    45.0     [100.00, 45.00]   True
2   2    37.0      [29.00, 38.00]  False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM