是否有一个函数来计算特定单词后面出现的元素?

2024-09-21 10:44:55 发布

您现在位置:Python中文网/ 问答频道 /正文

df
['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'pm*', 'tpm*', 'lep*']
['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'am*', 'te*', 'qe*','te*']
['ch*', 'co*', 'DePe*', 'ch*', 'DePe*', 'DePe*', 'tpm*', 'lep*']
['ch*', 'DePe*', 'eeae*', 'ps*', 'er*']
Name: df, Length: 4, dtype: object

我需要计算在“DePe*”的最后一个实例(从左到右)之后发生的项 我期待这样的结果。你知道吗

df                                                                    count
['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'pm*', 'tpm*', 'lep*']      3
['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'am*', 'te*', 'qe*','te*']  4
['ch*', 'co*', 'DePe*', 'ch*', 'DePe*', 'DePe*', 'tpm*', 'lep*']      2
['ch*', 'DePe*', 'eeae*', 'ps*', 'er*']                               3

Tags: namedfchamlengthpserte
3条回答

list.indexreversed一起使用:

my_df['count'] = [list(reversed(l)).index('DePe*') for l in my_df['df']]

                                                  df  count
0   [ch*, co*, DePe*, DePe*, DePe*, pm*, tpm*, lep*]      3
1  [ch*, co*, DePe*, DePe*, DePe*, am*, te*, qe*,...      4
2   [ch*, co*, DePe*, ch*, DePe*, DePe*, tpm*, lep*]      2
3                      [ch*, DePe*, eeae*, ps*, er*]      3

我是python新手,所以这个解决方案可能不是您想要的。但我认为这是可行的:

l1 = ['ch*', 'co*', 'DePe*', 'DePe*', 'DePe*', 'pm*', 'tpm*', 'lep*']
count=0
for x in l1:
    if x == 'DePe*':
        count=0
    else:
        count+=1
print (count)

apply与lambda函数和index的反向lists一起使用,效果很好,因为在python中列表是基于0的索引:

df['count'] = df['A'].apply(lambda x: x[::-1].index('DePe*'))
print (df)

                                                   A  count
0   [ch*, co*, DePe*, DePe*, DePe*, pm*, tpm*, lep*]      3
1  [ch*, co*, DePe*, DePe*, DePe*, am*, te*, qe*,...      4
2   [ch*, co*, DePe*, ch*, DePe*, DePe*, tpm*, lep*]      2
3                      [ch*, DePe*, eeae*, ps*, er*]      3

如果可能,某些值不存在,请在try-except语句中指定值:

def f(x):
    try:
        return x[::-1].index('DePe*')
    except ValueError:
        return np.nan #or return 0

df['count'] = df['A'].apply(f)

相关问题 更多 >

    热门问题