简体   繁体   中英

Add the values of a panda dataframe column if the value of another column is the same

I am still novice in python and I am hitting a wall, I cannot figure out how to add together the values in two lists depending on the value in another list. here is an example to illustrate my thought:

 list 1 = [1,1,1,2,2,3,3,3,4,4]
 list 2 = [4,7,6,5,4,7,7,3,5,6]

what i would like to do is get this: For every unique value in list 1 I want to sum up the values in list 2 at same position.

dic3 = {1:17, 2:9, 3:14, 4:11}

is it possible to do this with list only or do I need a dataFrame?

I have trying doing:

  for i in list1:
      if i== i-1:
           count1 =+ i
      else: 
          count1 = 1 

but it is super off and I do not seem to find a solution, even when I try to put the problem in a numpy array. Would somebody have a hint that could help the situation?

Thank you for your help, it is greatly appreciated.

The answer in your question is wrong, it should be 3:17

list1 = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4]
list2 = [4, 7, 6, 5, 4, 7, 7, 3, 5, 6]
prev = list1[0]
dict =  {}
sum = 0
for i in range(len(list1)):
    if prev == list1[i]:
        sum += list2[i]
    else:
        prev = list1[i]
        sum = 0
        sum+=list2[i]
    dict[prev] = sum
print(dict)

You can use numpy arrays to achieve your result.

list1 = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4]
list2 = [4, 7, 6, 5, 4, 7, 7, 3, 5, 6]

unique=set(list1)
arr1=np.array(list1)
arr2= np.array(list2)

dict={}
for val in unique:
    list2 = np.nonzero(arr1==val)
    dict[val]=arr2[list2[0]].sum()

print(dict)

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM