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

2024-05-05 19:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框

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])

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


Tags: 数据方法indataframedfforindexif
2条回答

您可以使用嵌套的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

使用^{}

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

相关问题 更多 >