1

I am new to Python and I was trying to create a loop which would create two lists of people based on the condition. My Dataframe has three columns:

controln donated amount_donated

controln is the ID of a person, donated means whether a person donated money or not

I'd like to have a list of people who donated more than $1 and another one which checks if they donated more than $5. I tried making a loop :

above5=[]
above1=[]

for a,c in val1.iterrows():
    a= val1['controln']
    b = val1['donated']
    c= val1['amount_donated']
    for item in c:
        if item >= 5 : 
          above5.append(a)
        if 5> item >= 1 :
            above1.append(a)
        else:
            print('No match')
print('Done') 

However it does not work as it creates a list of series with all the IDs and not those meeting the conditions. I tried also with above1.append((a,c)) but that also doesn't work.

Could anyone advise me on what should be changed?

atline
  • 28,355
  • 16
  • 77
  • 113
Antie
  • 11
  • 2

2 Answers2

2

You are interpreting a and c given by iterrows() incorrectly. The a gives you the index numbers while the c gives you the row. You can get the id from c[0], the donate boolean from c[1], and the amount donated from c[2]. Then you can use these and filter them out into appropriate lists using conditional statements. Also in python if 5> item >= 1 is an invalid conditional syntax.

You are also assigning the whole columns to a, b and c from the dataframe inside the loop by using statements such as a= val1['controln']. This is incorrect for your use case and also you should not reassign the a that you get from iterrows().

You also don't require a nested for loop for item in c: since it does not serve any purpose for your use case.

A correct sample code is as follows:

above5=[]
above1=[]

for a,b in df.iterrows():
    id = b[0]
    donate = b[1]
    val = b[2]
    
    if val >= 5: 
     above5.append(id)
    if val >= 1 and val < 5:
     above1.append(id)
    else:
     print('No match')
print('Done') 
CompEng007
  • 86
  • 8
0

iterrows() return the row id and the row see a simple example .

So you should do something like this:

for a,c in val1.iterrows():
    amount = c['amount_donated']
    if amount >= 5 : 
        above5.append(c['controln'])
    elif amount >= 1 :
        above1.append(c['controln'])
    else:
        print('No match')
print('Done') 

When you write: a = val1['controln'] and appending a to the list, you actually appending the entire column.

Kartoffelkultur
  • 190
  • 1
  • 11