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    
2
  • So you want all pairs of column name + value? Commented May 14, 2020 at 14:56
  • 1
    Does this answer your question? How to pivot a dataframe Commented May 14, 2020 at 15:01

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Beat me to it :D
to get the list you can add .tolist() after values
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))

Comments

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.