![](/img/trans.png)
[英]Create new column based on values from other columns / apply a function of multiple columns, row-wise in Pandas
[英]Pandas - create new column based on other columns, excluding first row
在名为“single_future_data”的数据框中,我想基于同一 df 的其他列创建一个新列“Ctr1”。
我想出了这个解决方案,它不是最优雅和最快的解决方案,但它做了它应该做的:
single_future_data['Ctr1'] = np.where(np.logical_and(single_future_data.Price_Prev3.notnull(), single_future_data.Price_Prev3.shift(1).notnull()), 'Price_Prev3',
np.where(np.logical_and(single_future_data.Price_Prev2.notnull(), single_future_data.Price_Prev2.shift(1).notnull()), 'Price_Prev2',
np.where(np.logical_and(single_future_data.Price_Prev1.notnull(), single_future_data.Price_Prev1.shift(1).notnull()), 'Price_Prev1',
np.where(np.logical_and(single_future_data.Price_C_1.notnull(), single_future_data.Price_C_1.shift(1).notnull()), 'Price_C_1',
np.where(np.logical_and(single_future_data.Price_C_2.notnull(), single_future_data.Price_C_2.shift(1).notnull()), 'Price_C_2',
np.where(np.logical_and(single_future_data.Price_C_3.notnull(), single_future_data.Price_C_3.shift(1).notnull()), 'Price_C_3', 'Price_C_4'))))))
我的问题是这个函数在第一行不起作用,我需要在第一行应用不同的函数。
我尝试使用此代码从第二行开始应用我的函数:
single_future_data['Ctr1'] =""
single_future_data.iloc [1:, 8] = np.where(np.logical_and(single_future_data.Price_Prev3.notnull(), single_future_data.Price_Prev3.shift(1).notnull()), 'Price_Prev3',
np.where(np.logical_and(single_future_data.Price_Prev2.notnull(), single_future_data.Price_Prev2.shift(1).notnull()), 'Price_Prev2',
np.where(np.logical_and(single_future_data.Price_Prev1.notnull(), single_future_data.Price_Prev1.shift(1).notnull()), 'Price_Prev1',
np.where(np.logical_and(single_future_data.Price_C_1.notnull(), single_future_data.Price_C_1.shift(1).notnull()), 'Price_C_1',
np.where(np.logical_and(single_future_data.Price_C_2.notnull(), single_future_data.Price_C_2.shift(1).notnull()), 'Price_C_2',
np.where(np.logical_and(single_future_data.Price_C_3.notnull(), single_future_data.Price_C_3.shift(1).notnull()), 'Price_C_3', 'Price_C_4'))))))
但是出现了以下错误:ValueError: could not broadcast input array from shape (79,) into shape (78,)
有任何想法吗? 谢谢
Ben.T 在评论中的解决方案运行良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.