繁体   English   中英

Python pandas 替换基于与列表项的部分匹配

[英]Python pandas replace based on partial match with list item

我有一个大的三列 dataframe 这种形式:

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#',
]

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

所需的 output:

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 被更新,因为与列表项存在部分匹配。 Refs 5, 14 保持原样。

如果Shaperefli中的所有条目都是字符串,则可以编写 function 以应用于Shaperef以转换它们:

def f(row_val, seq):
    for item in seq:
        if row_val in item:
            return item
    return row_val

然后:

# 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM