Home > Software engineering >  How to complete a serie index with a list?
How to complete a serie index with a list?

Time:05-02

I have this serie:

import pandas as pd
d = {'poste1': 1, 'poste3': 2, 'poste4': 1}
ser = pd.Series(data=d, index=['poste1', 'poste3', 'poste4'])
print(ser)

I would like to complete the value this the missing codification :

liste_poste=['poste1','poste2','poste3','poste4','poste5']

result expected : enter image description here

Does somebody have an idea ?

CodePudding user response:

You can reindex it and use the fill_value parameter to fill missing values with 0 (so that we don't mess up the dtype of the Series):

out = ser.reindex(liste_poste, fill_value=0)

Output:

poste1    1
poste2    0
poste3    2
poste4    1
poste5    0
dtype: int64

CodePudding user response:

If you convert the list to a series as well, you can use pandas' combine method for series:

series_poste = pd.Series({k: 0 for k in liste_poste})
ser = ser.combine(series_poste, func=np.add, fill_value=0)
print(ser)
poste1    1
poste2    0
poste3    2
poste4    1
poste5    0
dtype: int64

CodePudding user response:

After having the series, you can do something like this to get the list.

import pandas as pd
d = {'a': 1, 'b': 2, 'c': 1}
list_entries = ['a','b','c','d']
ser = pd.Series(data=d, index=['a', 'b', 'c'])
print(ser)
found = list(ser [ser  > 0].index)
print([x for x in list_entries if x not in found])

Output:

['d']
  • Related