我有一個資料框,例如:資料框存盤孩子們的電話號碼、最喜歡的食物和最喜歡的玩具(用不同的 ID 簽名)。資料在不同的行和列中是分開的。有些行可能只有 Id 而沒有別的。輸入可能如下所示:
|Id|phone_number|food |toy |
|--|------------|------|----|
|01| |apple | |
|01|9995552222 |banana| |
|01| | |ball|
|01|9995552222 |orange| |
|02|3332226666 | | |
|02| |boba | |
|02| | | |
我想得到什么:我想將不同行中的值組合在一起,使每一行都獨一無二。輸出可能如下所示:
|Id|phone_number|food |toy |
|--|------------|------|----|
|01|9995552222 |apple |ball|
|01|9995552222 |banana|ball|
|01|9995552222 |orange|ball|
|02|3332226666 |boba | |
謝謝
test = pd.DataFrame({'Id': ['01', '01', '01', '01', '02', '02', '02'],
'phone_number': ['', '9995552222', '', '9995552222', '3332226666', '', ''],
'food': ['apple', 'banana', '', 'orange', '', 'boba', ''],
'toy ': ['', '', 'ball', '', '', '', '']})
uj5u.com熱心網友回復:
您可以嘗試groupby Idcolumn 然后用bfill和填充 NaN 列ffill。最后洗掉“phone_number”、“food”、“toy”中的重復項。
test = test.replace('', pd.NA)
out = (test.groupby('Id')
.apply(lambda g: g.bfill().ffill())
.drop_duplicates(['phone_number', 'food', 'toy']) # 'toy ' in your given dataframe
.fillna('')
)
print(df)
Id phone_number food toy
0 01 9995552222 apple ball
1 01 9995552222 banana ball
2 01 9995552222 orange ball
4 02 3332226666 boba
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/477612.html
標籤:python-3.x 熊猫 数据框
