我的問題類似于this、this和this問題。
但是還是無法解決。
我有一個帶有重復 ID 的資料框
ID Publication_type
1 Journal
1 Clinical study
1 Guideline
2 Journal
2 Letter
我想讓它變寬,但我不知道我將擁有多少出版物型別 - 可能是 2 個,也可能是 20 個。因此,我不知道我需要多少個列寬。寬列的最大大小publication_type不得超過每個 id 的型別數。
預期輸出
ID Publication_type1 Publication_type2 Publication_type 3 etc
1 Journal Clinical Study Guideline
2 Journal Letter NaN
現在我不需要將相同的出版物型別放入同一列。我不需要同一列中的所有文章。謝謝!
uj5u.com熱心網友回復:
您可以 group by ID,聚合 via list,然后根據結果創建一個新的 DataFrame :
col = 'Publication_type'
new_df = pd.DataFrame(df.groupby('ID')[col].agg(lambda x: x.tolist()).tolist()).replace({None: np.nan})
new_df.columns = [f'{col}{i}' for i in new_df.columns 1]
new_df['ID'] = df['ID'].drop_duplicates().reset_index(drop=True)
輸出:
>>> df
Publication_type1 Publication_type2 Publication_type3 ID
0 Journal Clinical-study Guideline 1
1 Journal Letter NaN 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390612.html
