2

I've created a dataframe:

In [1]: import pandas as pd 

In [2]: import numpy as np

In [3]: df = pd.DataFrame({ 'Student_ID':['001','002','003','004','005'],
                'Amy'   : ['Amy',np.nan,np.nan,np.nan,'Amy'],
                'Brian' : [np.nan,'Brian',np.nan,np.nan,np.nan],
                'Cat'   : [np.nan,np.nan,np.nan,'Cat',np.nan]},columns=['Student_ID','Amy','Brian','Cat']) 


In  [4]:df
Out [4]:
    Student_ID  Amy Brian   Cat
0          001  Amy   NaN   NaN
1          002  NaN Brian   NaN
2          003  NaN   NaN   NaN
3          004  NaN   NaN   Cat
4          005  Amy   NaN   NaN

And next I'd like to return to a dataframe with two columns only, Student_ID and Name. How to convert to below in precise codes?

In [5]: df
Out[5]: 
  Student_ID    Name    
0        001     Amy    
1        002   Brian    
2        003     NaN    
3        004     Cat
4        005     Amy    

3 Answers 3

4

You can using dot

df.iloc[:,1:].notna().dot(df.columns[1:])
Out[78]: 
0      Amy
1    Brian
2         
3      Cat
4      Amy
dtype: object
#df['name']=df.iloc[:,1:].notna().dot(df.columns[1:])

Or bfill

df.iloc[:,1:].bfill(1).iloc[:,0]
Out[82]: 
0      Amy
1    Brian
2      NaN
3      Cat
4      Amy
Sign up to request clarification or add additional context in comments.

Comments

4

You could use groupby/first, since first selects the first non-NaN item in each group:

In [146]: df.set_index('Student_ID').unstack().groupby(level='Student_ID').first().rename('Name').reset_index()
Out[146]: 
  Student_ID   Name
0        001    Amy
1        002  Brian
2        003    NaN
3        004    Cat
4        005    Amy

Comments

2

Using .lookup

df['Name'] = df.lookup(df.index, df.iloc[:, 1::].notnull().idxmax(1))

  Student_ID  Amy  Brian  Cat   Name
0        001  Amy    NaN  NaN    Amy
1        002  NaN  Brian  NaN  Brian
2        003  NaN    NaN  NaN    NaN
3        004  NaN    NaN  Cat    Cat
4        005  Amy    NaN  NaN    Amy

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.