我有一个数据帧,其中每个单元格都包含一个列表。我有一个函数,旨在根据条件在每个列表中插入“1”。但是,我的代码并没有达到我的预期。
每个列表
s
由其他两个列表中的元素组成:(1)成员列表(2)非成员列表。我的目标是将数字“1”插入
S
当任何“成员”后接任意两个约定的“非成员”。最多应向添加一个“1”
S
. 这就是密码。
import pandas as pd
members = ['AA', 'BBB', 'CC', 'DDDD']
non_members = ['EEEE', 'FF', 'GGG', 'HHHHH', 'III', 'JJ']
s = ['AA', 'EEEE', 'GGG', 'FF']
df = pd.DataFrame({'string':[s]}) # each row of the column 'string' is a list
如此给出
S
:
['AA', 'EEEE', 'GGG', 'FF']
我试图达到的结果是:
['AA', '1', 'EEEE', 'GGG', 'FF']
这是我的代码:
d = df['string']
def func(row):
out = ""
look = 2
for i in range(len(row)-look):
out += row[i]
if (row[i] in members) & \
(row[i+1] in non_members) & \
(row[i+2] in non_members):
out += '1' + row[i+1:]
break
return out
e = d.apply(func)
print(e)
这仅给出以下结果:
string
dtype: object
但我想得到的是:
['aa'、'1'、'eeee'、'ggg'、'ff']
到那里最简单的方法是什么?
以上问题与本问题有关:
How to insert a character in a list, based on the consecutive appearance of two elements from another list? Python