# Appending values in Pandas column

I have a dictionary:

and a dataframe

df = pd.DataFrame({'q':['hey this is [a]', 'why dont you [b]', 'clas is [c]']})

I want to append the values from dictionary to the corresponding keys.

My expected output is:

q
0   hey this is [a](1234)
1  why dont you [b](2345)

Here's my solution:

x = {k: k+v for k,v in x.items()}

def das(data):
for i in x.keys():
if i in data:
data = data.replace(i, x[i])
return data

df['q'] = df['q'].apply(lambda x: das(x))
print(df)

Is there a way to improve this?

I have to update a dictionary by appending a key infront of values. Then I use apply to replace the values.

I am looking for more efficient solution.

• Are the keys always in the form shown in this example, i.e. surrounded by []? – Graipher Feb 19 at 15:24
• @Graipher yes..it's like markdown used in SE – AkshayNevrekar Feb 20 at 4:32

There is an alternative way using the str functions of pandas.Series, which has the advantage that they are usually faster. In this case you can use pandas.Series.str.replace, which can take a regex to match strings against and a callable to replace them with, which gets passed the regex match object:

def repl(m):
k = m.group()
return k + x[k]

df.q.str.replace(r'$.*$', repl)
# 0     hey this is [a](1234)
# 1    why dont you [b](2345)