如果其他条件在多个列上,则为 pandas [英] pandas if else conditions on multiple columns
本文介绍了如果其他条件在多个列上,则为 pandas 的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我的df以下:
import pandas as pd
data_dic = {
"a": [0,0,1,2],
"b": [0,3,4,5],
"c": [6,7,8,9]
}
df = pd.DataFrame(data_dic)
结果:
a b c
0 0 0 6
1 0 3 7
2 1 4 8
3 2 5 9
我需要根据条件将值从上述各列粘贴到新列中:
I need to past value to new column from above columns based on conditions:
if df.a > 0 then value df.a
else if df.b > 0 then value df.b
else value df.c
我现在尝试:
df['value'] = [x if x > 0 else 'ww' for x in df['a']]
但是不知道如何在其中输入更多条件.
but don't know how to input more conditions in this.
预期结果:
a b c value
0 0 0 6 6
1 0 3 7 3
2 1 4 8 1
3 2 5 9 2
感谢您的辛勤工作.
推荐答案
Difference between vectorized and loop solutions in 400k rows:
df = pd.concat([df] * 100000, ignore_index=True)
In [158]: %timeit df['value2'] = np.select([df.a > 0 , df.b > 0], [df.a, df.b], default=df.c)
9.86 ms ± 611 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
In [159]: %timeit df['value1'] = [x if x > 0 else y if y>0 else z for x,y,z in zip(df['a'],df['b'],df['c'])]
399 ms ± 52.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
这篇关于如果其他条件在多个列上,则为 pandas 的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文