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

How can i insert values from a list into a pandas data frame column?

i have this dataframe:

index x y
0 0 3
1 0.07 4
2 0.1 6
3 0. 13 5

i want to insert new x values to the x column

new_x = [0, 0.03, 0.07, 0.1, 0.13, 0.17, 0.2]

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

so that the dataframe becomes

index x y
0 0 3
1 0.03 NaN
2 0.07 4
3 0.1 6
4 0. 13 5
5 0. 17 NaN
6 0. 2 NaN

so basically for every new_x value that doesn’t exist in column x, the y value is NaN

is it possible to do it in pandas? thank you

>Solution :

You can use Numpy’s searchsorted.

After you create a new_y array that is the same length as the new_x array. You use searchsorted to identify where in the new_y array you need to drop the old y values.

new_y = np.full(len(new_x), np.nan, np.float64)
new_y[np.searchsorted(new_x, df.x)] = df.y

pd.DataFrame({'x': new_x, 'y': new_y})

      x    y
0  0.00  3.0
1  0.03  NaN
2  0.07  4.0
3  0.10  6.0
4  0.13  5.0
5  0.17  NaN
6  0.20  NaN
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