我有一个包含三列A,B和C的数据框。我必须创建第四列,名称为“ Differential_value”。我必须使用某些条件将值分配给此第四列。 条件如下:
1)第一个条件:如果A,B或C这三个列中的任何一个具有0值,则I在“ Differential_value”列中具有0。
2)否则,“ Differential_value”分配的值应为:
(max(A,B,C) - min(A,B,C))/min(A,B,C)
Below is my sample data:
A B C
10 7 0
10 8 12
9 8 11
10 11 12
13 5 0
0 3 10
12 8 11
12 9 7
11 10 9
10 11 9
下面是我尝试过的代码:
df['differential_value'] = np.where((df['A']==0)|(df['B']==0)|(df['C']== 0),0),(np.where((df[['A','B','C']].max() - df[['A','B','C']].min())/df[['A','B','C']].min()))
ValueError:应同时给出x和y或不给出
答案 0 :(得分:3)
将np.where
与以下逻辑配合使用。另外,如果您有一组要应用的列,那么:
cols= ['A','B','C']
df['Differential_value'] = (np.where(df[cols].eq(0).any(1), 0,
(df[cols].max(1) - df[cols].min(1))/df[cols].min(1)))
或者:
df['Differential_value'] = (((df[cols].max(1) - df[cols].min(1))/df[cols].min(1))
.replace(np.inf, 0))
print(df)
A B C Differential_value
0 10 7 0 0.000000
1 10 8 12 0.500000
2 9 8 11 0.375000
3 10 11 12 0.200000
4 13 5 0 0.000000
5 0 3 10 0.000000
6 12 8 11 0.500000
7 12 9 7 0.714286
8 11 10 9 0.222222
9 10 11 9 0.222222
答案 1 :(得分:1)
尝试一下:
def f(a,b,c):
if( a*b*c==0):
return 0
else:
return (max(a,b,c) - min(a,b,c))/min(a,b,c)
df['D'] = df.apply(lambda x: f(x['A'], x['B'], x['C']), axis=1)
A B C
0 10 7 0
1 10 8 12
2 9 8 11
3 10 11 12
4 13 5 0
5 0 3 10
6 12 8 11
7 12 9 7
8 11 10 9
9 10 11 9
A B C D
0 10 7 0 0.000000
1 10 8 12 0.500000
2 9 8 11 0.375000
3 10 11 12 0.200000
4 13 5 0 0.000000
5 0 3 10 0.000000
6 12 8 11 0.500000
7 12 9 7 0.714286
8 11 10 9 0.222222
9 10 11 9 0.222222