pandas - Python 从不同的行和列中获取 value

我有一个 dataframe 喜欢:dataframe stores 电话号码、最喜欢的食物和孩子最喜欢的玩具(使用不同的 ID 签名)。数据在不同的行和列中是分开的。有些行可能只有 Id 而没有别的。输入可能如下所示:

|Id|phone_number|food  |toy |
|--|------------|------|----|
|01|            |apple |    |
|01|9995552222  |banana|    |
|01|            |      |ball|
|01|9995552222  |orange|    |
|02|3332226666  |      |    |
|02|            |boba  |    |
|02|            |      |    |

我想得到什么:我想将不同行中的 value 组合在一起以使每一行都独一无二。输出可能如下所示:

|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', '', '', '', '']})

回答1

您可以尝试 groupby Id 列,然后用 bfillffill 填充 NaN 列。最后删除“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

相似文章

随机推荐

最新文章