且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

复杂曲线方程式在np.where使用中给出错误

更新时间:1970-01-01 07:57:00

让我们

expr = 14.6413819224756*(df['X']**0.5)+64.4092780704338*(np.log(df['X'])**-2)+1675.7498523727*(np.exp(-df['X']))+3.07221083927051*np.cos(df['X'])

然后您会发现您的代码是:

then you'll find out that your code is:

df['y']=np.where(df['Z']>=(expr,8,9))

df['Z']shape(10,),这意味着它是具有10行的一维pandas.Series对象.但是,(expr,8,9)是一个简单的tuple,其中包含3个项目(但是expr的确是10行pandas.Series).

The shape of df['Z'] is (10,), which means it is a one-dimensional pandas.Series object which has 10 rows. However, (expr,8,9) is a simple tuple which has 3 items (expr is indeed a 10-row pandas.Series however).

这就是提示为operands could not be broadcast together with shapes (10,) (3,) 的原因,因为numpy不知道如何将 10 pandas.Series 3 项目tuple.

That's why the hint is operands could not be broadcast together with shapes (10,) (3,) , since numpy doesn't know how to compare a 10-row pandas.Series with a 3-item tuple.

再次检查您的方程式,并对其进行修改以满足您的需求.

Check your equation again and get it modified to meet your needs.

更新:

根据注释,89np.where(condition,x,y)的两个参数,分别是xy.但是您错误地将它们放在df['Z']>=之后的expr中,这使得>=运算符将pandas.Seriestuple而不是两个pandas.Series进行比较.

According to the comment, the 8 and 9 are two arguments to np.where(condition,x,y) as the x and y. But you put them in the expr after df['Z']>= by mistake, which makes the >= operator compares a pandas.Series's with a tuple, but not two pandas.Series.

只需移动最后一个括号即可,代码将运行良好:

Just move the last parentheses and the code will work well:

df['y']=np.where(df['Z']>=(14.6413819224756*(df['X']**0.5)+64.4092780704338*(np.log(df['X'])**-2)
                      +1675.7498523727*(np.exp(-df['X']))+3.07221083927051*np.cos(df['X'])),8,9)

结果应为:

     X     Z  y
0   1.4     1  9
1   2.0  2000  8
2   3.0     3  9
3   4.0     4  9
4   5.0     5  9
5   6.0     6  9
6   7.0    70  8
7   8.0     8  9
8   9.0     9  9
9  10.0    10  9

更新2:

要在满足两个条件的情况下执行np.where,或者说要执行and,只需使用np.where((condition1) & (conditions),x,y).例如:

To do np.where while two conditions are met, or to say, an and operation, just use np.where((condition1) & (conditions),x,y). For example:

df['foo']=np.where((df['Z']>3) & (df['Z']<100),True,False)

请注意,&之前和之后的括号是必需的.您将通过数据获得此信息:

Note, the parentheses here before and after & is necessary. You'll get this with your data:

      X     Z           y    foo
0   1.4     1  999.999293  False
1   2.0  2000  380.275104  False
2   3.0     3  159.114194  False
3   4.0     4   91.481930   True
4   5.0     5   69.767368   True
5   6.0     6   63.030212   True
6   7.0    70   59.591631   True
7   8.0     8   56.422723   True
8   9.0     9   54.673108   True
9  10.0    10   55.946732   True