首页 > 解决方案 > 在数据框中的列表中查找元素的索引

问题描述

我有:

adj           response                                                   

"beautiful"    ["beautiful", "beautiful2", "beautifu3"]
"good1"        ["beautiful1", "beautiful2", "beautifu3"]
"hideous"      ["hideous23r", "hideous", "hidoeous"] 

我想要一个额外的列,其中包含上一列中项目的第一个索引:

adj           response                                                   index

"beautiful"    ["beautiful", "beautiful2", "beautifu3"]                    0
"not there"    ["beautiful1", "beautiful2", "beautifu3"]                   None
"hideous"      ["hideous23r", "hideous", "hidoeous"]                       1

标签: pythonpandasdataframe

解决方案


尝试:

df['response'] = df['response'].apply(eval) # do not use this if column dtype is list
df['index'] = df.apply(lambda x: None if x['adj'] not in x['response'] else x['response'].index(x['adj']),1)

输出:

         adj                             response  index
0  beautiful   [beautiful, beautiful2, beautifu3]    0.0
1      good1  [beautiful1, beautiful2, beautifu3]    NaN
2    hideous       [hideous23r, hideous, hideous]    1.0

推荐阅读