Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于列内条件的Dataframe列_Python_Pandas - Fatal编程技术网

Python 基于列内条件的Dataframe列

Python 基于列内条件的Dataframe列,python,pandas,Python,Pandas,我想创建一个新的df[“c”],并附带以下条件: 如果b进入(a±0.5a),则c=a 如果b不在(a±0.5a),则c=b 输出应为: a b 0 100 90 1 30 117 2 90 99 3 200 94 我认为需要使用由&创建的条件或链接的条件,或者: df['c']=np.where(df.eval(“0.5*a您只需要where这里,而且您的两个条件可以视为一个,所以我们只需要一次if--else(这是where)逻辑 df['c'

我想创建一个新的
df[“c”]
,并附带以下条件:

  • 如果b进入(a±0.5a),则c=a

  • 如果b不在(a±0.5a),则c=b

输出应为:

     a    b
0  100   90
1   30  117
2   90   99
3  200   94
我认为需要使用由
&
创建的条件或链接的条件,或者:


df['c']=np.where(df.eval(“0.5*a您只需要
where
这里,而且您的两个条件可以视为一个,所以我们只需要一次if--else(这是
where
)逻辑

df['c'] = np.where(df.eval("0.5 * a <= b <= 1.5 * a"), df.a, df.b)
#alternative 1
#df['c'] = np.where((df['b'] >= df.a.mul(1.5)) & (df['b'] <= df.a.mul(0.5)), df.a, df.b)
#alternative 2
#df['c'] =  np.where(df['b'].between(df.a.mul(0.5), df.a.mul(1.5)), df.a, df.b)

print (df)
     a    b    c
0  100   90  100
1   30  117  117
2   90   99   90
3  200   94   94
df['c']=df['a']
df.c=df.c.where((df.a*1.5>df.b)和(df.a*0.5这是使用访问器和

结果

df['c'] = df['b']

df.loc[df['b'].between(0.5*df['a'], 1.5*df['a']), 'c'] = df['a']
解释

  • 为序列设置默认值
  • 使用
    .loc
    更新您的特定标准
  • 如果您有进一步的条件,您可以根据其他答案切换到使用
    numpy.where
df['c']=df['a']
df.c=df.c.where((df.a*1.5>df.b)&(df.a*0.5<df.b),df.b)
df
Out[746]: 
     a    b    c
0  100   90  100
1   30  117  117
2   90   99   90
3  200   94   94
df['c'] = df['b']

df.loc[df['b'].between(0.5*df['a'], 1.5*df['a']), 'c'] = df['a']
     a    b    c
0  100   90  100
1   30  117  117
2   90   99   90
3  200   94   94