Home > Net >  efficient way to fill a series of zeros with values at specific positions
efficient way to fill a series of zeros with values at specific positions

Time:09-01

I would like to find an efficient way to fill a series of zeros with values at specific positions, based on the index. Here is some exemplary code:

import pandas as pd

dict_0 = {x: 0 for x in range(1, 11)}
ser_0 = pd.Series(dict_0)

dict_vals={2:0.1, 5:0.9}
ser_vals=pd.Series(dict_vals) 

ser_composed = pd.concat([ser_0[~ser_0.index.isin(ser_vals.index)],
ser_vals[ser_vals.index.isin(ser_vals.index)]])
ser_composed.sort_index()

As I want to apply it to much data, I'd like to find a way to do it more efficiently. Can anyone help me? Thanks a lot in advance!

CodePudding user response:

pd.Series.update is exactly what you're looking for.

Note: It always modifies the Series in place. If you don't want this, make a copy beforehand.

ser_0_original = ser_0.copy()

ser_0.update(ser_vals)

CodePudding user response:

Just in case you're creating a dataframe with zeros first to be filled afterwards, consider directly creating the series based on dict_vals, along the lines of

pd.Series(dict_vals, index=range(1,11)).fillna(0)

CodePudding user response:

You can also use broadcasting

ser_0[dict_vals.keys()] = list(dict_vals.values())

This will modify ser_0, if you want to preserve it use a copy

ser_composed = ser_0.copy()
ser_composed[dict_vals.keys()] = list(dict_vals.values())

Output

1     0.0
2     0.1
3     0.0
4     0.0
5     0.9
6     0.0
7     0.0
8     0.0
9     0.0
10    0.0
  • Related