python - 查询列表中的单词索引时出现意外输出
问题描述
因此,我将一次一行的数据框输入到函数中,以搜索单词的第一次出现并将其索引返回到新的数据框列中。
def fix_df(row):
words= row['t_sents']
tags= row['t_tags']
return find_start(words, tags) #get a row slice from two columns,
def find_start(words, tags):
try:
idx = tags.index('ante')
except ValueError:
idx = None
return idx
bant_df['start_ante'] = bant_df.apply(fix_df, axis=1) #calling the ff
然而,我的输出是出乎意料的。例如查看数据帧快照
t_sents t_tags start_ante
0 'Sandwich', 'in', 'Kent', ';', 'until', '2011... '0', '0', '0', '0', 'ante', 'ante', '0', '0',... 22.0
1 'If', 'the', 'deals', 'were', 'properly', 'ac... 'ante', 'ante', 'ante', 'ante', 'ante', 'ante... 2.0
2 'These', 'distortions', 'have', 'seen', 'one'... '0', '0', '0', '0', '0', '0', '0', '0', '0', ... 152.0
我在第一帧中的预期答案应该是 4,但我有 22。第二行应该是 0,但我有 2。可能有什么问题?请注意,我只查询了第二列 t_tags 中的单词。
解决方案
我认为在你的find_start
函数idx = tags.index('ante')
tags
中pandas.Series
不是 alist
所以index
方法的工作方式不同。tags
如果您通过这样做来获取数据,tags.values.tolist()
那么您可以使用list
index 方法来获得正确的结果。
我做了一个例子:
import pandas as pd
df = pd.DataFrame()
df['tags'] = ['0', '0', '0', '0', 'ante', 'ante', '0', '0']
type(df['tags'])
>>> pandas.core.series.Series
# you can get a list as
type(df['tags'].values.tolist()) # .values gets a numpy array which has a .tolist method
>>> list
df['tags'].values.tolist().index('ante')
>>> 4
推荐阅读
- r - 使用 R 的 changepoint 包检测均值和方差中的多个变化点
- python - 如何根据 Pandas 中特定值的一列转换仅在一列中具有唯一值的 DataFrame
- angular - 使测试订阅无效
- android - android NullPointerException 上的 SMS 身份验证
- java - 链表只给出一个指向要在单个链表中删除的节点的指针(删除代码差异)?
- php - Sylius 自定义模型不起作用
- swift - 如何在 Mapbox iOS 中将自定义注释的底部放置在特定坐标上
- javascript - 从外部 js 传递参数到 react prop
- java - org.codehaus.jackson.JsonParseException 同时反序列化字符串
- jar - 如何在 dcos spark run 中传递 jar 文件(来自 Artifactory)?