1

Apologies for the noobish question but....

I have a dataframe (in python using pandas, with headers) which looks like this:

   Pink     Blue    Yellow   Green  
 --------- ------- -------- ------- 
  Jackson   Bryan   Bruce    Benji  
  James     Jonah   Jenny    Kevin  
  Tyson     Jenna   Mike     none   
  Kendall   Amy     Alison   none   
  Ben       none    none     none   

How do I get a list of teams and names to look like below?

  Pink    Jackson  
  Pink    James    
  Blue    Bryan    
  ...              
  Green   Kevin    
  • So you want all pairs of column name + value? – L3n95 May 14 '20 at 14:56
  • 1
    Does this answer your question? [How to pivot a dataframe](https://stackoverflow.com/questions/47152691/how-to-pivot-a-dataframe) – Dave May 14 '20 at 15:01

2 Answers2

1

If I got it right, you want to have all pairs of column name + value. pd.melt can do that for you:

 df = pd.DataFrame({"Pink": ["Jackson", "James"], "Blue": ["Bryan", None]})
 pd.melt(df)

Result:

  variable    value
0     Pink  Jackson
1     Pink    James
2     Blue    Bryan
3     Blue     None

And if you only want a 2-dimensional numpy array you can do:

pd.melt(df).values

Result:

array([['Pink', 'Jackson'],
       ['Pink', 'James'],
       ['Blue', 'Bryan'],
       ['Blue', None]], dtype=object)

And as matman9 pointed out just add a .tolist() after the .values to get a python list.

L3n95
  • 1,505
  • 3
  • 25
  • 49
0

In addition to the earlier answer I'd suggest filtering out the None's:

for t in filter(lambda x: x[1], pd.melt(df).values.tolist()):
    print('{:8} {}'.format(*t))
Błotosmętek
  • 12,717
  • 19
  • 29