Python:将多个二进制列转换为单个分类列

2024-05-16 10:57:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含170列的csv文件数据集,前5列包含唯一标识符(平台、ID、日期、调用长度、名称)。其余的列175包含涵盖10个类别的二进制数据。我想压缩这些列,以便数据帧中的列数为15。包括以下示例:

import pandas as pd

df1 = pd.DataFrame({'Platform': ['Telephone', 'Chat', 'Text'], 'ID': [1, 2, 
3], 'Length': [1545,1532,1511], 'Name': ['andy', 'helen', 'peter'], 'Problem: 
A':[0,1,0], 'Problem: B':[1,0,0], 'Problem: C': [0,0,1], 'Solution: A': 
[0,1,0], 'Solution: B':[1,0,0], 'Solution: C': [0,0,1]})

输出为:

^{pr2}$

我希望数据帧看起来像:

  Platform ID Length  Name   Problem  Solution
  Telephone 1 1545    andy    B        B
  Chat      2 1532    helen   A        A
  Text      3 1511    peter   C        C

仅供参考,这不是完整的数据帧。总共有170个哥伦布,我想把它们转换成15个。在


Tags: csv数据textnameidchatlengthpeter
1条回答
网友
1楼 · 发布于 2024-05-16 10:57:23

您可以在列上使用groupby+apply和点积

df = df.set_index('Name')
df.groupby(df.columns.str.split(':').str[0], axis=1).apply(
    lambda x: x.dot(x.columns.str.split(': ').str[1])
)

      Problem Solution
Name                  
andy        B        B
helen       A        A
peter       C        C

相关问题 更多 >