1

I am new to pandas. I am facing an issue with null values. I have a list of 3 values which has to be inserted into a column of missing values how do I do that?

In [57]: df
Out[57]: 
   a   b   c  d  
0  0   1   2  3  
1  0 NaN   0  1  
2  0 Nan   3  4 
3  0   1   2  5  
4  0 Nan   2  6  
In [58]: list = [11,22,44]

The output I want

Out[57]: 
   a   b   c  d  
0  0   1   2  3  
1  0   11  0  1  
2  0   22  3  4 
3  0   1   2  5  
4  0   44  2  6  
1
  • 2
    what if you have more NaN values than elements in your list? (btw. don't redefine the built-in list) Commented Jan 26, 2021 at 16:35

2 Answers 2

3

If your list is same length as the no of NaN:

l=[11,22,44]
df.loc[df['b'].isna(),'b'] = l

print(df)

   a     b  c  d
0  0   1.0  2  3
1  0  11.0  0  1
2  0  22.0  3  4
3  0   1.0  2  5
4  0  44.0  2  6
Sign up to request clarification or add additional context in comments.

Comments

1

Try with stack and assign the value then unstack back

s = df.stack(dropna=False)
s.loc[s.isna()] = l # chnage the list name to l here, since override the original python and panda function and object name will create future warning 
df = s.unstack()
df
Out[178]: 
     a     b    c    d
0  0.0   1.0  2.0  3.0
1  0.0  11.0  0.0  1.0
2  0.0  22.0  3.0  4.0
3  0.0   1.0  2.0  5.0
4  0.0  44.0  2.0  6.0

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.