多条件if语句Pandas(代码未完成运行)

to94eoyn  于 2022-12-09  发布在  其他
关注(0)|答案(3)|浏览(114)

尝试根据其他列值在Pandas中创建多条件新列。
下面的代码不产生错误或结果(但会产生警告);它只是不停地运行:

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看起来像:

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

df ['new column']的格式应为:

['new column']
      0
      1
      0
     .4
bihw5rsg

bihw5rsg1#

这可能不是最好的解决方案,但是根据问题中提供的有限信息,这段代码至少生成了预期的输出:

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)
qyswt5oh

qyswt5oh2#

不要使用循环/apply,使用矢量代码:

df['new'] = (df['b'].div(df['a'].mask(df['a'].eq(0),df['b']))
             .fillna(0)
             )

输出量:

a     b  new
0     0     0  0.0
1     0  1000  1.0
2  1000     0  0.0
3  5000  2000  0.4
n53p2ov0

n53p2ov03#

与@葫芦不同,但原理相同:

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)

相关问题