Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
How do you join multiple rows into one row in pandas?

I have a list that I'm trying to add to a dataframe. It looks something like this:

list_one = ['apple','banana','cherry',' ', 'grape', 'orange', 'pineapple','']

If I add the list to a dataframe, using df = pd.DataFrame({'list_one':list_one}) it'll look like this:

       list_one
   -------------
   0   apple
   1   banana 
   2   cherry
   3  
   4   grape
   5   orange
   6   pineapple
   7  

I want the combine some of the rows into one row, so that the dataframe looks something like this:

       list_one
   -----------------------------
   0   apple, banana, cherry 
   1   grape, orange, pineapple

Is there a simple way to do this?

Thank you for taking the time to read my question and help in any way you can.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Try with groupby and agg:

>>> df.groupby(df.loc[df['list_one'].str.contains('\w+')].index.to_series().diff().ne(1).cumsum(), as_index=False).agg(', '.join)
                   list_one
0     apple, banana, cherry
1  grape, orange, pineapple
>>> 
over 4 years ago · Santiago Trujillo Report

0

Create mask for match words by Series.str.contains, invert by ~ and crate groups by Series.cumsum, filter only matched rows and pass to GroupBy.agg with join function:

m = df['list_one'].str.contains('\w+')
df = df[m].groupby((~m).cumsum(), as_index=False).agg(', '.join)
print (df)
                   list_one
0     apple, banana, cherry
1  grape, orange, pineapple
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!