Python根据列名和第一列值重新整形

时间:2017-08-04 19:57:47

标签: python dataframe

我想根据列名和第一列的值重塑数据框。例如,我想重塑这个数据框:

    import { Component, OnInit } from '@angular/core';
    import { NgForm } from '@angular/forms';
    import * as Rx from "rxjs";
    import {BehaviorSubject} from 'rxjs/BehaviorSubject';

    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })    
    export class HomeComponent {
      myBehavior: any;
      mySubject: BehaviorSubject<string>;
      received = "nothing";
      chatter: string[];
      nxtChatter = 0;
      constructor() {
        this.myBehavior = new BehaviorSubject<string>("Behavior Subject Started");
        this.chatter = [
          "Four", "score", "and", "seven", "years", "ago"
      ]        
    }        

      Start() {
        this.mySubject = this.myBehavior.subscribe(
          (x) => { this.received = x;},
          (err) => { this.received = "Error: " + err; },
          () => { this.received = "Completed ... bye"; }
        );
    }         

      Send() {
        this.mySubject.next(this.chatter[this.nxtChatter++]);
        if (this.nxtChatter >= this.chatter.length) {
           this.nxtChatter = 0;
           this.mySubject.complete();
        }    
       }    
    }        

进入以下数据框:

hours mon tue wed
0     3   4   5
1     6   7   8
2     9   10  11

提前致谢。

2 个答案:

答案 0 :(得分:2)

使用pandas.melt

import pandas as pd
pd.melt(df, id_vars='hours', var_name='day', value_name='target')

enter image description here

答案 1 :(得分:0)

我们也可以使用pd.lreshape

In [118]: cols = df.columns.drop('hours').tolist()

In [119]: pd.lreshape(df, {'target':cols}).assign(day=np.repeat(cols, len(df)))
Out[119]:
   hours  target  day
0      0       3  mon
1      1       6  mon
2      2       9  mon
3      0       4  tue
4      1       7  tue
5      2      10  tue
6      0       5  wed
7      1       8  wed
8      2      11  wed