python - 如何将熊猫数据框中的所有行与特定列的相同值合并?
问题描述
我有一个数据框,例如:
person_ID, first_name, last_name, feature_1, feature_2, feature_3
1, John, Talbert, 1,2,3
2, Ted, Thompson, 4,5,6
1, John, Talbert, 7,8,9
2, Ted, Thompson, 13,14,15
我想重新格式化它:
person_ID, first_name, last_name, feature_1_A, feature_2_A, feature_3_A, feature_1_B, feature_2_B, feature_3_B,
1, John, Talbert, 1,2,3, 7,8,9
2, Ted, Thompson, 4,5,6,13,14,15
知道什么是有效的方法吗?数据集很小,因此它实际上不必非常高效。
预先感谢您的帮助。
解决方案
这本质上是枢轴和重命名:
df['col'] = df.groupby('person_ID').cumcount()
out=df.pivot_table(index=['person_ID','first_name','last_name'],
columns='col', aggfunc='first')
out.columns = [f'{x}_{y}' for x,y in out.columns]
out = out.reset_index()
输出:
person_ID first_name last_name feature_1_0 feature_1_1 feature_2_0 feature_2_1 feature_3_0 feature_3_1
0 1 John Talbert 1 7 2 8 3 9
1 2 Ted Thompson 4 13 5 14 6 15
推荐阅读
- conan - 柯南 libbacktrace 包需要错误的 autoconf 版本
- python - 当适合我的模型时,我得到 ValueError: Input 0 of layer sequence is incompatible with the layer
- javascript - 为什么我的 HTML 代码返回 [object HTMLFormElement]?
- javascript - 将预定义的对象插入空白的 Javascript 数组
- python-3.x - 如何通过在 Python 中的其他列上放置条件语句,用同一列中的现有字符串替换列中的 NaN 值
- html - 在我的 html 导航栏中。我的条贴在边距的左侧。我该如何补救?
- javascript - Jest - UnhandledPromiseRejection - 收到的承诺已解决而不是被拒绝
- ios - 转义闭包的运行时间
- python - 无法正常运行服务器/项目结构不正确?
- amazon-web-services - 我们如何借助 AWS Glue PySpark 中的 Cobol 布局/文案来读取 MainFrame 文件