简体   繁体   English

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

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

I have a large three-column dataframe of this form:我有一个大的三列 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)
...

And a long list with entries like this:还有一个长长的列表,里面有这样的条目:

li = [
    'oval 60 [oval] [40]', 
    '(circle14,2) circ', 
    'square 20', 
    '126 18 square 921#',
]

I want to replace the entries in the Shaperef column of the df with a value from the list if the full Shaperef string matches any part of any list item.如果完整的 Shaperef 字符串与任何列表项的任何部分匹配,我想用列表中的值替换 df 的 Shaperef 列中的条目。 If there is no match, the entry is not changed.如果没有匹配项,则不会更改条目。

Desired output:所需的 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)
...

So refs 9, 10, 12 are updated as there is a partial match with a list item.因此,参考 9、10、12 被更新,因为与列表项存在部分匹配。 Refs 5, 14 stay as there are. Refs 5, 14 保持原样。

If Shaperef and all the entries in li are all strings you can write a function to apply over Shaperef to convert them:如果Shaperefli中的所有条目都是字符串,则可以编写 function 以应用于Shaperef以转换它们:

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

Then:然后:

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

This might not be a very quick way of doing this as it has a worst case run time of len(df) * len(li) .这可能不是一种非常快速的方法,因为它的最坏情况运行时间为len(df) * len(li)

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

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