我有一个看起来像这样的数据框 -
col_1 | col_2
-------------------
"red" | 21
-------------------
"blue" | 31
-------------------
"red" | 12
-------------------
"blue" | 99
-------------------
"blue" | 102
我也有一个像这样的值列表 label = [1,3,2]
我想构建第三列col_3
,如果颜色是“红色”,则应该有“是” ,否则在相应的行上应该有 1,3,2。基本上,如果颜色为“蓝色” ,则标签中的值应该一个接一个。col_1
预期输出-
col_1 | col_2 | col_3
---------------------------
"red" | 21 | "Yes"
-----------------------------
"blue" | 31 | "1"
------------------------------
"red" | 12 | "Yes"
------------------------------
"blue" | 99 | "3"
------------------------------
"blue" | 102 | "2"
我的方法-
我试过np.where()
像这样估算使用
np.where(df["col_1"]=="red","Yes",labels)
,但是
ValueError: operands could not be broadcast together with shapes
我相信这是由于df
和labels
(5 vs 3)的大小不同。
任何人都可以帮助我吗?
谢谢
编辑:
您可以尝试使用布尔掩码。首先,抢先分配Yes
给整个列,然后使用Series.ne
. 在您的情况下,创建一个col_1
值不等于的Red
掩码并使用该掩码填充值。
df['col_3'] = 'Yes'
m = df['col_1'].ne('Red') # ne -> not equal to
df.loc[m, 'col_3'] = label
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句