gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:53:56 24 4
gpt4 key购买 nike

我有一个数据框

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

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

最佳答案

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

关于python - 基于条件在数据框中创建列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46678109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com