I have two following lists:
indexList = [5,3,2,2,7,1]
valueList = [1,2,3,4,5,6]
I want to sort the two together, so that the output is:
indexList = [1,2,2,3,5,7]
valueList = [6,3,4,2,1,5]
Then, I want to fill-in the missing indices and their corresponding values as "0":
indexList = [1,2,2,3,4,5,6,7]
valueList = [6,3,4,2,0,1,0,5]
Lastly, I want to remove repeated indices and sum their values:
indexList = [1,2,3,4,5,6,7]
valueList = [6,7,2,0,1,0,5]
Would there be a built-in module to perform such task? Could any one guide me with piece of wisdom?
You can use pandas:
import pandas as pd
indexList = [5,3,2,2,7,1]
valueList = [1,2,3,4,5,6]
s = pd.Series(valueList, index= indexList)
s = s.groupby(s.index).sum().reindex(np.arange(s.index.min(), s.index.max()+1), fill_value=0)
print(s.index.tolist())
print(s.tolist())
Output:
[1, 2, 3, 4, 5, 6, 7]
[6, 7, 2, 0, 1, 0, 5]
groupby with sum to combine like indexes summing the value.reindex the series from the min of the series index to the
max of the series index and use fill_value parameter to fill
missing indexes with 0 values.tolist.tolist.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With