首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python熊猫基于列表项部分匹配的替换

Python熊猫基于列表项部分匹配的替换
EN

Stack Overflow用户
提问于 2021-05-16 12:19:13
回答 1查看 281关注 0票数 2

我有一个大的三列数据格式:

代码语言:javascript
运行
复制
Ref    Colourref      Shaperef      
5      red 12         square 15
9      14 blue        (circle14,2)  
10     6 orange 12    18 square
12     pink1,7        [oval] [40]
14     [green]        (rectsq#12,6)
...

还有一个长长的列表,上面有这样的条目:

代码语言:javascript
运行
复制
li = [
    'oval 60 [oval] [40]', 
    '(circle14,2) circ', 
    'square 20', 
    '126 18 square 921#',
]

如果完整的Shaperef字符串匹配任何列表项的任何部分,我希望用列表中的值替换df的Shaperef列中的条目。如果没有匹配项,则不会更改该项。

期望产出:

代码语言:javascript
运行
复制
Ref    Colourref      Shaperef      
5      red 12         square 15
9      14 blue        (circle14,2) circ  
10     6 orange 12    126 18 square 921#
12     pink1,7        oval 60 [oval] [40]
14     [green]        (rectsq#12,6)
...

因此,参考文献9,10,12是更新的,因为有一个部分匹配与一个列表项目。参考文献5,14待在那里。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-16 12:32:19

如果Shaperefli中的所有条目都是字符串,则可以编写一个函数通过Shaperef应用来转换它们:

代码语言:javascript
运行
复制
def f(row_val, seq):
    for item in seq:
        if row_val in item:
            return item
    return row_val

然后:

代码语言:javascript
运行
复制
# read in your example
import pandas as pd
from io import StringIO

s = """Ref    Colourref      Shaperef      
5      red 12         square 15
9      14 blue        (circle14,2)  
10     6 orange 12    18 square
12     pink1,7        [oval] [40]
14     [green]        (rectsq#12,6)
"""
li = [
    "oval 60 [oval] [40]",
    "(circle14,2) circ",
    "square 20",
    "126 18 square 921#",
]
df = pd.read_csv(StringIO(s), sep=r"\s\s+", engine="python")

# Apply the function here:
df["Shaperef"] = df["Shaperef"].apply(lambda v: f(v, li))
#    Ref    Colourref             Shaperef
# 0    5       red 12            square 15
# 1    9      14 blue    (circle14,2) circ
# 2   10  6 orange 12   126 18 square 921#
# 3   12      pink1,7  oval 60 [oval] [40]
# 4   14      [green]        (rectsq#12,6)

这可能不是一种非常快速的方法,因为它有一个最坏的运行时的len(df) * len(li)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67556583

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档