簡體   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