![](/img/trans.png)
[英]New column in Pandas dataframe based on value of variable in existing column
[英]Assinging variable value to a new column in pandas DataFrame
我使用某些条件创建了 3 个新变量 a、b 和 c。 现在我想再次使用某些条件将这些变量分配给 pandas DataFrame 中的新列。
我想要一个类似于我在下面编写的代码,但以更智能的方式。 下面的代码运行良好,但它不是一个聪明的解决方案。 有没有可能写一个循环,也许是一个迭代循环
df2['dest_col'] = np.where(df2['month'] == 'March-2016',a
,(np.where(df2['month'] == 'April-2016',b
,(np.where(df2['month'] == 'May-2016',c)))
你想要numpy.select
:
cond=[(df2['month'] == month) for month in df2['month'].unique()]
values=[a, b, c]
df2['dest_col'] = np.select(cond,values)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.