1

I need help with realisation of the following logic: While grouping a DataFrame I want certain columns to be concatenated with another text. For example:

Input:

id | col1 | col2
---|------|------
1  |  A   | 12
1  |  B   | 43
---|------|-----

After applying something like df.groupby(id).concatrows("text_"+col1+":"+col2.astype(str)), the desired output should be:

id | new col
---|-----------------------
1  | text_A:12;text_B:43   
---|-----------------------

So it should be kind of ";".join(), but with more flexibility.

2 Answers 2

2

One option could be the following:

df.groupby('id').apply(lambda g: ';'.join('text_' + g.col1 + ':' + g.col2.astype(str)))

Output:

id
1    text_A:12;text_B:43
Sign up to request clarification or add additional context in comments.

Comments

0

Another option is to concatenate col1 and col2 first before concatenating groups,

("text_" + df['col1'] + ":" + df['col2'].astype(str)).groupby(df['id']).apply(';'.join)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.