Dynamic If statement generation in python

I need to generate an if statement in python based on the number of unique values in a dataframe column. See below. Can you please suggest a way that I can accomplish this? if one unique value in …

问题描述:

I need to generate an if statement in python based on the number of unique values in a dataframe column. See below. Can you please suggest a way that I can accomplish this?

if one unique value in column it should generate

    if a>0: 
        print(a)  

if two unique values in column it should generate

    if a>0 and b>0: 
        print(a + b)
    if a=0 and b>0: 
        print(b)
    if a>0 and b=0: 
        print(a)

if three unique values in column it should generate

    if a>0 and b>0 and c>0: 
        print(a + b + c)
    if a=0 and b>0 and c>0: 
        print(b + c)
    if a>0 and b=0 and c>0: 
        print(a + c)
    if a>0 and b>0 and c=0: 
        print(a + b)
    if a=0 and b=0 and c>0: 
        print(c)
    if a>0 and b=0 and c=0: 
        print(a)
    if a=0 and b>0 and c=0: 
        print(b)

Essentially I need 2^n – 1 statements generated for n unique values.

解决方案 1:[1]

Don’t use multiple variables. Put all the values in a list, then you can loop over it:

print(sum(i for i in list_of_values if i > 0))

解决方案 2:[2]

You don’t need to write special cases for 0 because you are summing the values and 0 doesn’t affect the outcome. Either way, just look at positive numbers, find the unique values > 0 and then sum

df.my_column[df.my_column > 0].unique().sum()

参考链接:

Copyright Notice: This article follows StackOverflow’s copyright notice requirements and is licensed under CC BY-SA 3.0.

Article Source: StackOverflow

[1] Barmar

[2] tdelaney

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年4月29日
下一篇 2023年4月29日

相关推荐