Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) + ')'
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading