[英]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.