Home > Net >  How to find list Sum of 2 series in python
How to find list Sum of 2 series in python

Time:12-14

i have 2 series 1 containt value is list, and this list containt index of the 2nd series, i'll call it s1 and s2

s1

CountryCode
AE                        [2732106, 9635221, 497740020]
AO                                           [18840483]
AR    [19136618, 154821146, 5545580, 2516804, 197338...
AT    [54970390, 1186432, 53811920, 1401273, 1569597...
AU    [7360236, 2976616, 32871583, 21057806, 9644163...
                            ...                        
US    [3905732, 31524829, 7436630, 23584966, 1943672...
VC                                           [50572551]
VE                                [63119929, 232097737]
VN    [38482291, 180126717, 42255333, 22783399, 2533...
ZA    [2995297, 27387504, 596746008, 158195886, 4941...
Name: User ID, Length: 98, dtype: object

s2

User ID
203           2
375           2
488           2
901           3
1488          1
             ..
939075670     1
952945375     1
956833984     2
978555178     1
1035878080    1
Name: ID, Length: 3019, dtype: int64

How can i find sum of s1 list base on s2 list without using for loop?

the output i want like this

ex: i'll find sum of AE  # first row, s3 is a series result

s3.loc['AE'] = s2.iloc[2732106]   s2.iloc[9635221]  s2.iloc[497740020]

thanks

CodePudding user response:

s1 = pd.Series([[0,1,2],[3,4,5]], index=['a','b'])
s2 = pd.Series(range(10,16), index=range(6))
s1

out:
a    [0, 1, 2]
b    [3, 4, 5]
dtype: object
s2

out:
0    10
1    11
2    12
3    13
4    14
5    15
dtype: int64
s3 = s1.apply(lambda value_of_s1: sum([s2.loc[index_in_list] for index_in_list in value_of_s1]))

s3
out:
a    33
b    42
dtype: int64

CodePudding user response:

explode -> merge -> groupby.sum by @Chris

  • Related