0

I have a dataframe which looks like:

df = 
 |Name Nationality Family etc.....
0|John Born in Spain. Wife
1|nan But live in England son
2|nan nan daughter

Some columns only have one row but others have multiple answers over a few rows, how could i merge the rows onto each other so it would look something like the below:

df = 
 |Name Nationality Family etc....
0|John Born in Spain. But live in England Wife Son Daughter
asked Aug 12, 2020 at 11:38
1
  • whats the logic of join? pretty simple to do. Assuming any nan values under Name mean it belongs to most recent value? if so df['Name'].ffill().groupby('Name').agg(' '.join) should do the trick - you may need to specify your columns and join types if you have numbers,dates etc. Commented Aug 12, 2020 at 11:44

1 Answer 1

1

Perhaps this will do it for you:

import pandas as pd
# your dataframe
df = pd.DataFrame(
 {'Name': ['John', np.nan, np.nan],
 'Nationality': ['Born in Spain.', 'But live in England', np.nan],
 'Family': ['Wife', 'son', 'daughter']})
def squeeze_df(df):
 new_df = {}
 for col in df.columns:
 new_df[col] = [df[col].str.cat(sep=' ')]
 return pd.DataFrame(new_df)
squeeze_df(df)
# >> out: 
# Name Nationality Family
# 0 John Born in Spain. But live in England Wife son daughter

I made the assumption that you only need to do this for one single person (i.e. squeezing/joining the rows of the dataframe into a single row). Also, what does "etc...." mean? For example, will you have integer or floating point values in the dataframe?

answered Aug 12, 2020 at 16:24
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.