Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace values from second row onwards in a pandas pipe method

I am wondering how to replace values from second row onwards in a pipe method (connecting to the rest of steps).

import pandas as pd
import numpy as np

df = pd.DataFrame(
    {
        "Date": ["2020-01-01", "2021-01-01", "2022-01-01"],
        "Pop": [90, 70, 60],
    }
)

         Date  Pop
0  2020-01-01   90
1  2021-01-01   70
2  2022-01-01   60

Current solution

df.iloc[1:] = np.nan

Expected output

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

         Date  Pop
0  2020-01-01   90
1  2021-01-01  NaN
2  2022-01-01  NaN

>Solution :

You can also use assign like this:

df.assign(Pop=df.loc[[0], 'Pop'])

Output:

         Date   Pop
0  2020-01-01  90.0
1  2021-01-01   NaN
2  2022-01-01   NaN

Note: assign works with nice column headers, if your headers have spaces or special characters you will need to use a different method.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading