简体   繁体   中英

How to make complicated replacement of values in string column using dictionary?

I have a dictionary in pandas dataframe form:

name     value 
phil      1
andy      4
allen     5

and a table which looks like this:

phil/andy    
allen

I want to replace values in it by value from first table:

1/4    
5

how to do that?

Data:

df = pd.DataFrame({'name': {0: 'phil', 1: 'andy', 2: 'allen'},
                   'value': {0: 1, 1: 4, 2: 5}})

df1 = pd.DataFrame({'names': {0: 'phil/andy', 1: 'allen'}})

Code

d = dict(zip(df['name'], df['value'].astype(str)))    
df1['replaced'] = df1['names'].str.replace("\\w+", lambda x:d.get(x[0]), regex=True)

df1
      names replaced
0  phil/andy      1/4
1      allen        5

Here's a way to do what your question asks:

def foo(x):
    df['some_column'] = df['some_column'].str.replace(str(x['name']), str(x['value']))

dfNames.apply(foo, axis=1)

Sample input:

    name  value
0   phil      1
1   andy      4
2  allen      5

  some_column
0   phil/andy
1       allen

Sample output:

  some_column
0         1/4
1           5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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