简体   繁体   English

将变量值分配给 pandas DataFrame 中的新列

[英]Assinging variable value to a new column in pandas DataFrame

I have created 3 new variables a,b and c using certain conditions.我使用某些条件创建了 3 个新变量 a、b 和 c。 Now I want to assign these variables to a new column in a pandas DataFrame again using some conditions.现在我想再次使用某些条件将这些变量分配给 pandas DataFrame 中的新列。

I want a code something like what I have written below but in a smarter way.我想要一个类似于我在下面编写的代码,但以更智能的方式。 The code below is working fine but it's not a smart solution.下面的代码运行良好,但它不是一个聪明的解决方案。 Is there a possibility to write a loop, maybe an iterative loop有没有可能写一个循环,也许是一个迭代循环

df2['dest_col'] = np.where(df2['month'] == 'March-2016',a
                  ,(np.where(df2['month'] == 'April-2016',b
                  ,(np.where(df2['month'] == 'May-2016',c)))

You want numpy.select :你想要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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM