rootoor
rootoor

Reputation: 25

Pandas - How to append data to a column?

Likely makes sense to for loop this, but I don't know what Pandas functions to use. I want to take data from one column and append it to another in parenthesis:

col1 col2
A 1
B 2
col1 col2
A (1) 1
B (2) 2

Upvotes: 0

Views: 43

Answers (1)

Andrey Lukyanenko
Andrey Lukyanenko

Reputation: 3851

You can use an apply function that will work for each row:

df = pd.DataFrame({'col1': ['A', 'B'], 'col2': [1, 2]})
df.apply(lambda x: f'{x.col1} ({x.col2})', axis=1)

Or you could use a vectorized solution:

df['col1'] + ' (' + df['col2'].astype(str) + ')'

Upvotes: 1

Related Questions