0

I have a dataframe like this

col1   0    1   2   3   4   5   6   7   8   9   10  11
 a     NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
 b     NaN  NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
 c     x    y   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
 a     k    NaN NaN z   NaN NaN NaN NaN NaN NaN NaN NaN
 h     NaN  x   NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

I want to change it into:

col1   col2
 a     NaN
 b     NaN
 c     x   
 c     y
 a     k
 a     z
 h     x

Any help please?

2
  • does order matter? Commented Jan 16, 2018 at 1:26
  • No, but just consistency of the columns, i.e {[a,NAN], [c,x],.....etc.} Commented Jan 16, 2018 at 1:29

1 Answer 1

2

You can try this

df=df.set_index('col1')
df.loc[df.isnull().sum(1)==df.shape[1],0]='NaN'
df.stack().reset_index(level=1,drop=True).replace('NaN',np.nan).to_frame('col2').reset_index()
Out[544]: 
  col1 col2
0    a  NaN
1    b  NaN
2    c    x
3    c    y
4    a    k
5    a    z
6    h    x
Sign up to request clarification or add additional context in comments.

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.