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
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.