我有資料框,其中包含用戶行為中的步驟/操作。提供樣品。有很多步驟。每個步驟包含兩列:副標題和維度。我需要為每個步驟新列合并列副標題和維度 - 如果維度為空,則僅保留副標題,如果不保留僅維度。
所以新列 step0 值:如果 df['dimension1 (step0)'] 不是空值,則使用 df['dimension1 (step0)] 如果 df['dimension 1 (step0)] 為空,則使用 df['subtitle (step0) '] 然后重復第 1 步。
我是完全的新手。
預期輸出:
df['step0'] 的值:客戶端、主頁、df['step1'] 的內部值:客戶端、客戶端、地圖
等等
請提供代碼幫助
uj5u.com熱心網友回復:
假設idVisit是索引。然后你可以.combine_first()在每一個奇數列 ( dimension) 和每一個偶數列 ( ) 上嘗試方法subtitle:
# set the index just in case
df.set_index('idVisit', inplace=True)
# loop over subtitles and dimensions zipped together and enumerated
for n, (subtitle, dimension) in enumerate(zip(df.columns[0::2], df.columns[1::2])):
df[f'step {n}'] = df[dimension].combine_first(df[subtitle])
# show only added columns
df.iloc[:, 8:]
輸出:
# only the added columns are shown
step 0 step 1 step 2 step 3
idVisit
1 client client client client
2 homepage client homepage client
3 internal map internal map
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/525777.html
標籤:Python熊猫数据框
