Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing and sorting two lists [closed]

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?

like image 806
user7288808 Avatar asked Aug 10 '26 15:08

user7288808


1 Answers

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]

Details

  • Create a pandas series using valuesList as the data and indexList as the index of the series.
  • Use groupby with sum to combine like indexes summing the value.
  • Next, 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.
  • Print series index tolist.
  • Print series values tolist.
like image 106
Scott Boston Avatar answered Aug 13 '26 04:08

Scott Boston