【问题标题】:How to transform values into columns after group by in pandas?如何在熊猫分组后将值转换为列?
【发布时间】:2016-03-09 19:35:11
【问题描述】:

例如:

输入:

    column1
A   value1
A   value2
A   value2
B   value3
B   value3

输出:

    value1   value2   value3
A   1        1        0
B   0        0        1

【问题讨论】:

  • 你在哪里尝试这样做?
  • 真的喜欢吗?这个问题的三个答案……你自己试过吗?答案超级简单。比以下所有答案都简单。

标签: python pandas


【解决方案1】:

方法#0,刚刚被另一个问题提醒,你可以使用pd.crosstab

>>> pd.crosstab(df.index, df.column1).astype(bool).astype(int)
column1  value1  value2  value3
row_0                          
A             1       1       0
B             0       0       1

方法#1:你可以使用get_dummiesgroupby

>>> pd.get_dummies(df.column1)
   value1  value2  value3
A       1       0       0
A       0       1       0
A       0       1       0
B       0       0       1
B       0       0       1
>>> pd.get_dummies(df.column1).groupby(level=0).sum()
   value1  value2  value3
A       1       2       0
B       0       0       2

为您提供细胞计数,类似

>>> pd.get_dummies(df.column1).groupby(level=0).max()
   value1  value2  value3
A       1       1       0
B       0       0       1

方法#2:添加一个虚拟列,然后进行数据透视:

>>> d2 = df.reset_index()
>>> d2["dummy"] = 1
>>> d2.pivot_table("dummy", "index", "column1")
column1  value1  value2  value3
index                          
A             1       1     NaN
B           NaN     NaN       1
>>> d2.pivot_table("dummy", "index", "column1", fill_value=0)
column1  value1  value2  value3
index                          
A             1       1       0
B             0       0       1

【讨论】:

    【解决方案2】:

    找到了一个更简单的方法:

    df = df.groupby('id', as_index=False).agg({'column1': lambda x: x.tolist()})
    cols = sorted(list(set(df['column1'].sum())))
    for c in cols:
        df[c] = 1
    sessions[cols] = [1 if val in df['column1'] else 0 for val in cols] 

    【讨论】:

      【解决方案3】:
      for val in df['column1'].unique():
          df[val] = df['column1']==val
      df.groupby(df.index).any().drop('column1', axis=1)
      

      如果您需要将 True/False 转换为 1/0,您可以这样做:

      df.applymap(lambda x: 1 if x else 0)
      

      【讨论】:

        猜你喜欢
        • 2020-10-05
        • 2020-10-30
        • 2016-11-22
        • 2020-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-06
        • 1970-01-01
        相关资源
        最近更新 更多