1

I have the following dataframe:

df = pd.DataFrame({
         'user_a':['A','B','C',np.nan],
         'user_b':['A','B',np.nan,'D']
})

current df

I would like to create a new column called user and have the resulting dataframe:

complete df

What's the best way to do this for many users?

2 Answers 2

3

Use forward filling missing values and then select last column by iloc:

df = pd.DataFrame({
         'user_a':['A','B','C',np.nan,np.nan],
         'user_b':['A','B',np.nan,'D',np.nan]
})

df['user'] = df.ffill(axis=1).iloc[:, -1]
print (df)
  user_a user_b user
0      A      A    A
1      B      B    B
2      C    NaN    C
3    NaN      D    D
4    NaN    NaN  NaN
Sign up to request clarification or add additional context in comments.

Comments

0

use .apply method:

In [24]: df = pd.DataFrame({'user_a':['A','B','C',np.nan],'user_b':['A','B',np.nan,'D']})

In [25]: df
Out[25]: 
  user_a user_b
0      A      A
1      B      B
2      C    NaN
3    NaN      D

In [26]: df['user'] = df.apply(lambda x: [i for i in x if not pd.isna(i)][0], axis=1)

In [27]: df
Out[27]: 
  user_a user_b user
0      A      A    A
1      B      B    B
2      C    NaN    C
3    NaN      D    D

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.