Home > OS >  Pandas - How to append data to a column?
Pandas - How to append data to a column?

Time:07-19

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

CodePudding user response:

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)   ')'
  • Related