我有一个大的三列数据格式:
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列中的条目。如果没有匹配项,则不会更改该项。
期望产出:
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待在那里。
发布于 2021-05-16 12:32:19
如果Shaperef和li中的所有条目都是字符串,则可以编写一个函数通过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)。
https://stackoverflow.com/questions/67556583
复制相似问题