首页 > 解决方案 > 查询列表中的单词索引时出现意外输出

问题描述

因此,我将一次一行的数据框输入到函数中,以搜索单词的第一次出现并将其索引返回到新的数据框列中。

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 中的单词。

标签: pythonpandaslistre

解决方案


我认为在你的find_start函数idx = tags.index('ante') tagspandas.Series不是 alist所以index方法的工作方式不同。tags如果您通过这样做来获取数据,tags.values.tolist()那么您可以使用listindex 方法来获得正确的结果。

我做了一个例子:

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

推荐阅读