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
答案 0 :(得分:2)
将apply
与lambda函数一起使用,并将index
的{{1}}反向使用,则效果很好,因为列表在python中是基于0的索引:
lists
如果可能,某些值可能不存在,可以在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
答案 1 :(得分:1)
将list.index
与reversed
一起使用:
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
答案 2 :(得分:0)
我是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)