python - 在 Pandas 中创建新列时将相同 ID 的多行合并为一行
问题描述
假设有一个这样的数据框:
东西_ID | 描述 | Col1 | Col2 |
---|---|---|---|
id1 | 描述1 | 1.1 | 0.1 |
id1 | 描述2 | 1.1 | 2.1 |
id1 | 描述3 | 1.1 | 3.1 |
id2 | 描述1 | 8.1 | 1.1 |
id2 | 描述4 | 8.1 | 5.1 |
id2 | 描述2 | 8.1 | 2.1 |
如果同一 ID 的列中有不同的值,我想将此数据帧压缩为一个 ID 单行格式,同时创建新列。输出数据框应该是这样的:
东西_ID | Col1 | Desc1_Col2 | Desc2_Col2 | Desc3_Col2 | Desc4_Col2 |
---|---|---|---|---|---|
id1 | 1.1 | 0.1 | 2.1 | 3.1 | 钠 |
id2 | 8.1 | 1.1 | 2.1 | 钠 | 5.1 |
使用“描述”列创建新列名。如果每个 ID 组在列中具有相同的值,我们将保留该列而不进行修改,但只保留一条记录。
我得到的第一个想法是遍历列。但实际场景有很多列和行,这种方法可能需要很长时间,因为它有很多步骤。
由于我是 Pandas 的新手,我对如何应用它的功能没有足够的了解。我也找不到任何与此相关的有用链接。
所以我希望有人可以帮助我解决这个问题。
先感谢您!
- -更新 - -
我在这个问题中找到了一种有用的方法: 如何制作宽格式的数据框,从现有的列名中创建新的列名?
它解决了我的部分问题。但我的另一个要求是保持该列不变,如果 ID 组在该特定列中具有相同的值。我们不能一起做吗?我必须遵循单独的功能吗?
解决方案
选择部分:
cols=df.filter(like='Col').columns
exclude=['Col1','Col4']
#These are the columns that you want to kept like Col1
计算部分:
out=df.pivot_table(cols,'Something_ID','Description').swaplevel(axis=1)
includecols=~out.columns.get_level_values(1).isin(exclude)
newdf=out.loc[:,~includecols].droplevel(0,1).groupby(level=0,axis=1).first()
out=out.loc[:,includecols]
out.columns=out.columns.map('_'.join)
out=newdf.join(out).reset_index()
的输出out
:
Something_ID Col1 Desc1_Col2 Desc2_Col2 Desc3_Col2 Desc4_Col2
0 id1 1.1 0.1 2.1 3.1 NaN
1 id2 8.1 1.1 2.1 NaN 5.1
我使用的示例数据框:
df=pd.DataFrame({'Something_ID': {0: 'id1', 1: 'id1', 2: 'id1', 3: 'id2', 4: 'id2', 5: 'id2'},
'Description': {0: 'Desc1',
1: 'Desc2',
2: 'Desc3',
3: 'Desc1',
4: 'Desc4',
5: 'Desc2'},
'Col1': {0: 1.1, 1: 1.1, 2: 1.1, 3: 8.1, 4: 8.1, 5: 8.1},
'Col2': {0: 0.1, 1: 2.1, 2: 3.1, 3: 1.1, 4: 5.1, 5: 2.1},
'Col3': {0: 0.3, 1: 6.3, 2: 9.3, 3: 3.3, 4: 15.3, 5: 6.3},
'Col4': {0: 0.6, 1: 12.6, 2: 18.6, 3: 6.6, 4: 30.6, 5: 12.6}})
推荐阅读
- javascript - 如何检测没有另一个换行符的换行符?
- ios - 我的 CN1 应用程序在启动时崩溃
- python - 模块 sys 在 Python 3.6.6 上没有 _MEIPASS 成员错误
- sql - 重叠日期 - 开始日期应该是结束日期的第二天
- android - 无法从导航抽屉中显示我的活动
- javascript - 如何在刷新时自动根据多列过滤表格而不会丢失输入框中的文本?
- android - 浮动操作按钮上的阴影
- amazon-web-services - 如果将 kubeadm init 与 --cloud-provider=aws 标志一起使用,则 kubernetes 控制器管理器错误
- python - python中的平面序列可以有'in'运算符吗?
- java - Android Paging Library 如何知道加载更多数据?