How to replace only NaN values in a column, with a specific function?

Viewed 57

I have a dataframe that looks like this:

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

I would like to apply something like this code, to NaN values in article_id column:

from datetime import datetime
date = datetime.strftime(datetime.now(), "%Y%m%d%H%M")
df['article_id'] = [int(date + str("0"*(3-len(str(i)))) + str(i)) + 1 for i, k in df.reset_index().iterrows()]

Instead of `datetime.now() I would like to start the 1st january. I would like to have a value for the variable date = '202101011348' for example

And in final result I would like to have the same length as row 4 and 5 for article_id column and start to a precise date (202101011348)

I tought doing this:

df[df['article_id'].isna()]

And then apply the code above.

Expected output:

article_id          title
'202101011404106'   title_1
'202101011404107'   title_2
'202101011404108'   title_3
'202102011404103'   title_4
'202102011404104'   title_5
'202101011404109'   title_6

But how to apply this directly to the df, only to NaN values in the article_id column ?

1 Answers

You can use apply and lambda to achieve your goal.

Here I'm applying the now() function to NaN but it can be any method you want.

import pandas as pd
import numpy as np
from datetime import datetime

df = pd.DataFrame({
    "article_id": [np.NaN, np.NaN, np.NaN, "202101011212", "202101011313"], 
    "title": ["title_1", "title_2", "title_3", "title_4", "title_5"]
})

|------------------------------------------|
|   | article_id                 | title   |
|---|----------------------------|---------|
| 0 | NaN                        | title_1 |
| 1 | NaN                        | title_2 |
| 2 | NaN                        | title_3 |
| 3 | 202101011212               | title_4 |
| 4 | 202101011313               | title_5 |
|------------------------------------------|

df["article_id"] = df3["article_id"].apply(lambda x: datetime.now() if pd.isna(x) else x)

|------------------------------------------|
|   | article_id                 | title   |
|---|----------------------------|---------|
| 0 | 2021-02-03 13:16:29.438263 | title_1 |
| 1 | 2021-02-03 13:16:29.438269 |title_2  |
| 2 | 2021-02-03 13:16:29.438270 |title_3  |
| 3 | 202101011212               |title_4  |
| 4 | 202101011313               | title_5 |
|------------------------------------------|
Related