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

标签 python pandas binary categorical-data

我有一个包含 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]})

输出为:

df.head()

ID  Date        Length\\
1   2015-10-16    1545
2   2015-10-09    1532
3   2015-10-13    1511 

Name Problem: A Problem: B  Problem: C  Solution: A Solution: B Solution: C
andy         0          1           0            0           1           0
helen        1          0           0            1           0           0
peter        0          0           1            0           0           1

我希望数据框看起来像什么:

  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 列。

最佳答案

您可以将 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

关于Python:将多个二进制列转换为单个分类列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008428/

相关文章:

python - 返回给定字典键的下一个键,python 3.6+

binary - 帮助!我不知道二进制、十六进制、八进制和按位

java - 二分查找总是返回-1?

python - 如何用python解码colnames pandas dataframe?

python - '编程错误 : function avg(character varying) does not exist' - Django project

python - 为什么这两个表在Python中不连接?

python - Pandas 数据帧 : How to take the difference between observations with multiple observations per agent and stacked agents

mysql - 为什么这个字符串到二进制的转换不起作用?

python - Google 应用引擎静态文件处理程序示例

python - Pandas 按层次多重索引分组,不丢失其他索引