繁体   English   中英

基于条件在数据框中创建列

[英]Creating a Column in a Dataframe Based on a Conditional

我有一个数据框

pd.DataFrame({"A":[0,1,0,1],
          "B":[-1,0,0,0],
          "C":[0,0,0,0]},
         index = [.1,.2,.3, .4])

我首先在逻辑上解决问题的方式

for index, row in iterrows():
    if df['A'] == 1:
        df['C'] == 1
    elif df['B'] == -1
        df['C'] == -1
    else:
        df['C'] == 0

我想要

pd.DataFrame({"A":[0,1,0,1],
          "B":[-1,0,0,0],
          "C":[-1,1,0,1]},
         index = [.1,.2,.3, .4])

在尝试了第一种方法之后,我尝试了在其他问题中提出的多种方法,但似乎没有一种适合我的问题。

使用numpy.select

df['C'] = pd.np.select([df.A == 1, df.B == -1], [1, -1])

df
#       A    B   C
#0.1    0   -1  -1
#0.2    1    0   1
#0.3    0    0   0
#0.4    1   -1   1

您可以使用嵌套的np.where调用:

df.C = np.where(df.A == 1, 1, np.where(df.B == -1, -1, 0))
df
     A  B  C
0.1  0 -1 -1
0.2  1  0  1
0.3  0  0  0
0.4  1  0  1

性能

df = pd.concat([df] * 100000)

%timeit np.select([df.A == 1, df.B == -1], [1, -1])
100 loops, best of 3: 5.25 ms per loop

%timeit np.where(df.A == 1, 1, np.where(df.B == -1, -1, 0))
100 loops, best of 3: 2.86 ms per loop

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM