0

I have a dataframe like this:

article_id title NaN title_1 NaN title_2 NaN title_3 '202102011404103' title_4 '202102011404104' title_5 NaN title_6 

Firstly I would like to add a condition 'if there is NaN value do the following' (else do nothing). If there is NaN value in the column: I would like to add directly an incremental value to NaN values in the column with something like this:

x = 1 df.insert(0, 'article_id', range(x, x + len(df))) 

But I don't know how to add directly the code above to the column article_id, only to NaN values. How can I do it ?

Expected output:

article_id title 1 title_1 2 title_2 3 title_3 '202102011404103' title_4 '202102011404104' title_5 4 title_6 
2
  • Can you add expected output? Commented Feb 4, 2021 at 13:08
  • 1
    Hello, I updated my post Commented Feb 4, 2021 at 13:10

1 Answer 1

2

You can create mask for compare missing values and pass range with first value with count of NaNs by sum:

m = df['article_id'].isna() x = 1 df.loc[m, 'article_id'] = range(x, x + m.sum()) print (df) article_id title 0 1 title_1 1 2 title_2 2 3 title_3 3 '202102011404103' title_4 4 '202102011404104' title_5 5 4 title_6 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.