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