简体   繁体   中英

Return a Matching Element from a List in a Pandas Data Frame

I have a list of integers (gtin) and a pandas data frame (df) with one column containing a list in each row (df['gtins'])

I would like to define a new column in the data frame (df['gtin_match']) that returns the first matching element in the data frame list to the standalone list.

I have tried using the code below with the apply function and a lambda function, but it returns a list of the list in df['gtins'].

How can I fix this?

gtin = [1234, 456, 2005, 91]

df['gtin_match'] = df['gtins'].apply(lambda x: [x for i in range(0, len(x)) if int(x[i]) in gtin])

在此处输入图片说明

在您的理解中,您应该返回x[i]因为x本身是列表对象,而您只想返回 int:

df['gtin_match'] = df['gtins'].apply(lambda x: [x[i] for i in range(0, len(x)) if int(x[i]) in gtin])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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