Multiply rows in pandas DataFrame depending on values from c

Viewed 90

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.

2 Answers
result = (
    df.set_index("nname")
    .stack()
    .to_frame("eemail")
    .query("eemail != 'NO'")
    .droplevel(1)
    .reset_index()
)

Try this:

(df.mask(df.eq('NO'))
 .set_index('nname')
 .stack()
 .droplevel(1)
 .reset_index(level=0,name = 'eemail'))

Output:

   nname              eemail
0   Stan    stan@example.com
1   Stan   stan1@example.com
2  Danny   danny@example.com
3  Danny  danny1@example.com
4  Danny  danny2@example.com
5  Danny  danny3@example.com
6   Elle    elle@example.com
Related