Skip to content
Advertisement

Multiply rows in pandas DataFrame depending on values from c

I would like to get from this:

nname eemail email2 email3 email4
Stan stan@example.com NO stan1@example.com NO
Danny danny@example.com danny1@example.com danny2@example.com danny3@example.com
Elle elle@example.com NO NO NO

To this:

nname eemail
Stan stan@example.com
Stan stan1@example.com
Danny danny@example.com
Danny danny1@example.com
Danny danny2@example.com
Danny danny3@example.com
Elle elle@example.com

I know I can create 4 separate DFs with name and email column, then merge all 4 and drop the ones with ‘NO’ but I feel there might be smarter and more dynamic solution for this.

Advertisement

Answer

result = (
    df.set_index("nname")
    .stack()
    .to_frame("eemail")
    .query("eemail != 'NO'")
    .droplevel(1)
    .reset_index()
)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement