![](/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.