Home > Software engineering >  Multi Conditional if Statement Pandas (code doesn't finish running)
Multi Conditional if Statement Pandas (code doesn't finish running)

Time:12-08

Trying to create a multi-conditional new column in pandas based on other column values.

The following code doesn't produce an error or results (but it does produce warnings); it just keeps running:

for val1,val2 in zip(df['a'], df['b']):
    if val1 == 0 and val2 == 0:
        df['new_column'] = 0
    elif val1 in df['a'] == 0:
      
        df['new_column'] = 1
    else:
        for val2 in df['b']:
            if val2 ==0:
                df['new_column'] = 0
            else:
                df['new_column'] = df['b'] /  df['a']

df looks like:

['a']    ['b']
  0        0  
  0      1000
1000       0
5000     2000

expecting df['new column'] to be like:

['new column']
      0
      1
      0
     .4

CodePudding user response:

This might not be the most elegant solution, but based on the limited information provided in the question, this code at least generates your expected output:

def myfunc(row):
    if row['a'] == 0 and row['b'] == 0:
        result = 0
    else:
        if row['a'] == 0:
            result = 1
        elif row['b'] == 0:
            result = 0
        else:
            result = row['b'] / row['a']
    return result

df['new column'] = df.apply(myfunc, axis=1)

CodePudding user response:

Different in detail from @cucurbit but same principle:

def vals(x, y):
    if x == 0 and y == 0:
        return 0
    if x == 0 :
        return 1
    if y == 0:
        return 0
    else:
        return y/x

df['new column'] = df.apply(lambda x : vals(x['a'], x['b']), axis =1)
  • Related