3

I want to concatenate two rows in a DataFrame into one row. My current code:

import pandas as pd

df = pd.DataFrame(columns = ['string1', 'string2'])
df.loc[len(df), :] = ['Hello', 'This is Sam']
df.loc[len(df), :] = ['how are you?', 'from Canada']

#create the next row: ['Hello how are you?', 'This is Sam from Canada']

How to do it?

You can test the code here.

2
  • Hi, please post some example data and what the result should look like Commented Mar 15, 2019 at 13:30
  • You asked "How to concatenate rows..." but you really meant "How to string-concatenate multiple text columns...?" Since you want to string-concatenate string1 column between rows 1 and 2, e.g. 'This is Sam' + 'from Canada'. That's concatenating columns not rows, and it's string-concatenation (multiple strings into one string, not the usual concatenating multiple rows into one dataframe containing multiple rows). Commented Jun 17, 2019 at 20:49

1 Answer 1

4

Use agg with append:

df = df.append(df.agg(' '.join), ignore_index=True)
df

              string1                  string2
0               Hello              This is Sam
1        how are you?              from Canada
2  Hello how are you?  This is Sam from Canada
Sign up to request clarification or add additional context in comments.

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.