Home > Enterprise >  Python If-statement "if something is in the row that is not 0, return..."
Python If-statement "if something is in the row that is not 0, return..."

Time:04-20

I have this project where I want to analyze how many poems I have written. In an excel sheet I created (amongst others) three columns. They are called "cleaned poem", "cleaned additional poem 1" and "cleaned additional poem 2". If I didn't write a poem or additional poems that day the cell contains a 0.

I want to write an if clause to return something if the value in the cell is 0 and something different if the value is not 0, hence contains a poem.

My previous attempt is this (it doesn't work, the colum that gets printed either shows the value "day with two poems" or "NaN").

    def poems_per_day(row):
if row ['cleaned poem'] == 0:
    return 'day without poem'
elif (row['cleaned poem'] is not None):
    return 'day with one poem'
if row ['cleaned additonal poem 1'] == 0:
    return 'day with one poem'
elif (row['cleaned additional poem 1'] is not None):
    return 'day with two poems'
if row ['cleaned additional poem 2'] == 0:
    return 'day with one poem'
elif (row['cleaned additional poem 1'] is not None):
    return 'day with two poems'

CodePudding user response:

The bug could be with certain values not falling in either of the if or elif conditions. Since your goal is just to check if the cell contains '0', perhaps you could just replace all the elif statements with an else.

For instance:

def poems_per_day(row):
    if str(row['cleaned poem']) == '0':
        return 'day without poem'
    else:
        return 'day with one poem'
    if str(row['cleaned additonal poem 1']) == '0':
        return 'day with one poem'
    else:
        return 'day with two poems'
    if str(row['cleaned additional poem 2']) == '0':
        return 'day with one poem'
    else:
        return 'day with two poems'

CodePudding user response:

It is working now with this statement:

def poems_per_day_if_stat (row):
    if str(row['cleaned additional poem 2']) != '0':
        return 'day with three poems'
    elif str(row['cleaned additional poem 1']) != '0':
        return 'day with two poems'
    elif str(row['cleaned poem']) != '0':
        return 'day with one poem'
    else : 
        return 'day without poem'


poetry['poems per day if-stat'] = poetry.apply(lambda row: poems_per_day_if_stat(row), axis = 1)
  • Related