简体   繁体   English

如果在 Pandas 数据框中包含子字符串,则替换整个字符串,但包含值列表

[英]Replace Whole String if it contains substring in pandas dataframe, but with a list of values

Is there a way to do what is done is the below question, but instead of using a single string value, use a dict/array to replace many values in less lines of code?有没有办法做下面的问题,但不是使用单个字符串值,而是使用字典/数组来替换更少代码行中的许多值?

Replace whole string if it contains substring in pandas 如果包含熊猫中的子字符串,则替换整个字符串

What I have so far:到目前为止我所拥有的:

key = [
    {
        "substr": ["foo1", "foo2"],
        "new_val": "bar"
    },
]

for i in range(len(key)):
    df.loc[df[column].str.contains('|'.join(key[i]['substr'])), column] = key[i]['new_val']

can it be improved?可以改进吗?

Try:尝试:

for el in key:
    df[column]=df[column].str.replace('.*('+ '|'.join(el["substr"]) +').*', el["new_val"], regex=True)

Outputs (dummy data):输出(虚拟数据):

import pandas as pd

key = [
    {
        "substr": ["foo1", "foo2"],
        "new_val": "bar"
    }
]

df=pd.DataFrame({"x": ["foo1xyz", "abcfoo", "zyc", "foyo2foo2g"], "y": [1,2,3,4]})

for el in key:
    df["x"]=df["x"].str.replace('.*('+ '|'.join(el["substr"]) +').*', el["new_val"], regex=True)

>> df

        x  y
0     bar  1
1  abcfoo  2
2     zyc  3
3     bar  4

暂无
暂无

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

相关问题 如果整个字符串包含熊猫数据框中的子字符串,则替换整个字符串 - Replace whole string if it contains substring in pandas dataframe 替换包含大熊猫整个数据框中子字符串的整个字符串 - Replace whole string which contains substring in whole dataframe in pandas 如果它包含熊猫中的子字符串,则替换整个字符串 - Replace whole string if it contains substring in pandas 如果列表中的字符串在 Pandas DataFrame 列中包含 ZE83AED3DDF4667DEC0DAAAACB2BB3BE0BZ,如何替换它 - How to replace a string in a list if it contains a substring in Pandas DataFrame column 如果熊猫数据框中包含特定的子字符串,请替换该字符串 - Replace string in pandas dataframe if it contains specific substring 如何过滤包含Pandas DataFrame Python中传递列表中所有substring的df列中的值? - How to filter values in columns of df that contains all substring in passed list in Pandas DataFrame Python? 用列表中的子字符串替换 Pandas 列中的字符串 - Replace string in Pandas column by substring from list Pandas:将列表值替换为来自另一个数据帧的一串值 - Pandas: Replace list value to a string of values from another dataframe Python替换Dataframe字符串和非子字符串中的整个值 - Python Replace Whole Values in Dataframe String and Not Substrings 如果熊猫数据框中包含特定的子字符串,则替换它的列值 - Replacing column values in a pandas dataframe based if it contains a specific substring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM