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?
CodePudding user response:
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
CodePudding user response:
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