【问题标题】:Perform cross transformations for all except current value对除当前值之外的所有值执行交叉转换
【发布时间】:2020-11-03 02:06:19
【问题描述】:

我有以下数据集:

ID  Animal
1   Dog
1   Cat
1   Turtle
2   Turkey
2   Dog
2   Cat
3   Tiger
3   Antelope

我的目标本质上是创建一个交叉表,但是我想将 ID 和动物的每个组合视为唯一 ID,这样我会得到以下输出。

不幸的是,我正在使用 python2.7,所以它必须在那里兼容。

【问题讨论】:

    标签: python pandas python-2.7


    【解决方案1】:

    尝试.get_dummiesjoin 输出到数据框

    df.join(pd.get_dummies(df.Animal))
    
    
    
        ID    Animal  Antelope  Cat  Dog  Tiger  Turkey  Turtle
    0   1       Dog         0    0    1      0       0       0
    1   1       Cat         0    1    0      0       0       0
    2   1    Turtle         0    0    0      0       0       1
    3   2    Turkey         0    0    0      0       1       0
    4   2       Dog         0    0    1      0       0       0
    5   2       Cat         0    1    0      0       0       0
    6   3     Tiger         0    0    0      1       0       0
    7   3  Antelope         1    0    0      0       0       0
    

    【讨论】:

      【解决方案2】:

      使用pivot,然后用concat填充

      df = pd.concat([df,df.pivot(columns='animal',values='animal').notnull().astype('int').fillna(0)],axis=1)
      print(df)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-24
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        • 1970-01-01
        • 2014-03-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多