1

I have a Pandas DataFrame with columns that contain data for some rows and not for others. I need to merge several columns into a single column, removing missing data. For example:

   Name     Preference_1 Preference_2 Preference_3 Preference_4
0  Dave        Beach         Lake     Mountain       Desert
1  Jeff     Outdoors          NaN          NaN          NaN
2   Tom       Forest        Ocean        Swamp          NaN

Needs to become this:

   Name   Preference
0  Dave      Beach
1  Dave       Lake
2  Dave   Mountain
3  Dave     Desert
4  Jeff   Outdoors
5  Tom      Ocean
6  Tom      Swamp
7  Tom     Forest
3
  • 3
    why do Ocean, Swamp move from Tom to Jeff in the output? Commented Dec 18, 2019 at 21:15
  • you want melt Commented Dec 18, 2019 at 21:15
  • @AndyL. You're right that was a typo thank you Commented Dec 18, 2019 at 21:55

1 Answer 1

2

Use DataFrame.melt:

( df.melt('Name',value_name='Preference')
    .drop('variable',axis=1)
    .dropna()
    .sort_values('Name')
    .reset_index(drop=True) )

or DataFrame.stack with DataFrame.set_index:

df.set_index('Name').stack().rename('Preference').reset_index(level=['Name',0],drop=0)

Output

   Name Preference
0  Dave      Beach
1  Dave       Lake
2  Dave   Mountain
3  Dave     Desert
4  Jeff   Outdoors
5   Tom     Forest
6   Tom      Ocean
7   Tom      Swamp
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much

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.