【问题标题】:How to add a character to a list if two items from another list appear consecutively? Python如果另一个列表中的两个项目连续出现,如何将字符添加到列表中? Python
【发布时间】:2018-05-24 01:33:50
【问题描述】:

我有一个 DataFrame,其中每个单元格都包含一个列表。我有一个函数,旨在根据条件在每个列表中插入一个“1”。但是,我的代码并没有达到我的预期。

每个列表s 包含来自其他两个列表的元素:(1) 成员列表 (2) 非成员列表。我的目标是在任何“成员”后面跟着任何两个“非成员”时将数字“1”插入ss 最多应添加一个“1”。这是代码。

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

【问题讨论】:

    标签: python-3.x dataframe


    【解决方案1】:

    对于这个问题,您的答案是通过以下方式更改您的函数func

    def func(row):
        look = 2
        for i in range(len(row)-look):
            if (row[i] in members) & \
               (row[i+1] in non_members) & \
               (row[i+2] in non_members):
                # if the condition is met, return the list with the 1 added where you want
                return row[:i+1] + ['1'] + row[i+1:]
        # in case you never met your condition, you return the original list without changes
        return row
    

    您的问题是您在func 中混合了strlist 输入

    【讨论】:

    • @twhale 很高兴它有效。正如你所说你是初学者,我建议你看看如何使用熊猫的强大功能,在单元格中列出一个列表并不是最好的方法,你的相关问题的答案可能会更快。因为这种方式可行,但是如果您达到大数据集,则可能需要一段时间:)
    • 非常感谢,还有很多我不明白的地方,但我也会通过 pandas 逐步提高,感谢您的提示!
    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 1970-01-01
    • 2017-09-28
    • 1970-01-01
    • 2018-02-12
    • 2019-09-22
    • 1970-01-01
    • 2021-12-22
    相关资源
    最近更新 更多