0

I have the following data frame:

dataset = {
     'String': ["ABCDEF","HIJABC","ABCHIJ","DEFABC"],
    'Bool':[True,True,False,False],
    'Number':[10,20,40,50]}

df = pd.DataFrame(dataset)



      String   Bool  Number
0  ABCDEF   True      10
1  HIJABC   True      20
2  ABCHIJ  False      40
3  DEFABC  False      50

I would like to sum the rows of the column Number where Bool is False to the rows where Bool is True:

The rows can be matched and summed together if the reverse of String of one row is not equal to the String of the row.

  • In this case ABCHIJ where bool is False is not equal to the reverse of ABCDEF so I sum the numbers: 10+40.

  • HIJABC where Bool is True is summed to DEFABC where Bool is False the outcome is 70

Expected output:

    String   Bool  Number
0  ABCDEF   True      50
1  HIJABC   True      70
2  ABCHIJ  False      40
3  DEFABC  False      50

I hope my explanation was good enough, is there a way to achieve the above outcome ?

5
  • Your explanation is unclear, what is the summation condition? Also, what have you tried to do it? Commented Aug 15, 2022 at 17:31
  • How does this scale when say you have another row 4 XYZ False 70? Commented Aug 15, 2022 at 17:43
  • @FoundABetterName, there would not be a 4th row... I expect for it to be a group of 4 rows everytime. Commented Aug 15, 2022 at 18:06
  • Will there be 2 Trues and 2 Falses always? Commented Aug 15, 2022 at 18:06
  • but DEFABC is not reversed string of ABCDEF !!! Commented Aug 15, 2022 at 18:08

1 Answer 1

1

One way is like this:

df_true = df[df['Bool'] == True]
df_false = df[df['Bool'] == False]

for i in df_false['String']:
   idx = df_true[df_true['String'] != (i[3:] + i[:3]) ].index[0]
   current_num = df.loc[df.index == idx, 'Number'].values[0]
   added_num = df[df['String'] == i]['Number'].values[0]
   df.loc[df.index == idx, 'Number'] =  current_num + added_num

I hope it helps

Sign up to request clarification or add additional context in comments.

1 Comment

thank you man, I really appreciate your help. It worked, this is what I've been looking for. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.