python - 在数据框中的列表中查找元素的索引
问题描述
我有:
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
解决方案
尝试:
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
推荐阅读
- javascript - 如何在 Plasma 5 等离子团上进行无限异步循环
- apache - Apache tika:MSG 删除结果字符串中的额外换行符
- java - 如何获得基于 java maven 的程序的测试覆盖率?
- android - Kotlin:如何创建/附加文件(和共享)
- c# - DataGridView 不显示来自 DataTable C# 的列
- powershell - 如何批量重命名文件夹中的文件,以便删除之前和包括“_”的所有字符
- javascript - 单击每个项目中的“x”按钮删除任何网格项目,我的方法只删除最后一个
- flask - 散景服务器如何从 server_document() 访问参数
- macos - 登录重定向循环中的 Gitlab 客户端
- regex - 如何在 Google Sheets 中合并两个数组查询的代码