【问题标题】:Value error in assigning values to dataframe column using "np.where" condition使用“np.where”条件将值分配给数据框列时出现值错误
【发布时间】:2019-05-14 04:53:00
【问题描述】:

我有一个包含三列 A、B 和 C 的数据框。我必须创建名为“Differential_value”的第四列。我必须使用某些条件为第四列赋值。 条件如下:

1) 第一个条件:如果 A、B 或 C 三列中的任何一列的值为 0,则“Differential_value”列中的 I 为 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 要么都给出,要么都不给出

【问题讨论】:

  • 下面是我的尝试: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 都应该给出或都不给出

标签: python pandas


【解决方案1】:

按照以下逻辑使用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

【讨论】:

  • 解决方案很好,只添加cols = ['A','B','C']np.where(df[cols].eq(0).any(1), 0, (df[cols].max(1) - df[cols].min(1))/df[cols].min(1))这样的子集
  • @jezrael 感谢您的建议,已添加到解决方案中。
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2013-11-08
    • 2018-06-12
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多