Pandas DataFrame重塑为xyz格式

时间:2017-09-05 07:56:09

标签: pandas dataframe reshape

如果我有以下数据框:

   11-May  12-May  13-May  14-May  Distance
0       1       6      11      16        10
1       2       7      12      17        20
2       3       8      13      18        30
3       4       9      14      19        40
4       5      10      15      20        50

并且,我想重新组织为三个列,如:

    Distance variable  value
0         10   11-May      1
1         20   11-May      2
2         30   11-May      3
3         40   11-May      4
4         50   11-May      5
5         10   12-May      6
6         20   12-May      7
7         30   12-May      8
8         40   12-May      9
9         50   12-May     10
10        10   13-May     11
11        20   13-May     12
12        30   13-May     13
13        40   13-May     14
14        50   13-May     15
15        10   14-May     16
16        20   14-May     17
17        30   14-May     18
18        40   14-May     19
19        50   14-May     20

我怎样才能在熊猫中做到这一点?

1 个答案:

答案 0 :(得分:3)

使用unstack

的一种方法
In [1940]: dff.set_index('Distance').unstack().reset_index()
Out[1940]:
   level_0  Distance   0
0   11-May        10   1
1   11-May        20   2
2   11-May        30   3
3   11-May        40   4
4   11-May        50   5
5   12-May        10   6
6   12-May        20   7
7   12-May        30   8
8   12-May        40   9
9   12-May        50  10
10  13-May        10  11
11  13-May        20  12
12  13-May        30  13
13  13-May        40  14
14  13-May        50  15
15  14-May        10  16
16  14-May        20  17
17  14-May        30  18
18  14-May        40  19
19  14-May        50  20

使用melt

的另一种方法
In [1943]: dff.melt('Distance')
Out[1943]:
    Distance variable  value
0         10   11-May      1
1         20   11-May      2
2         30   11-May      3
3         40   11-May      4
4         50   11-May      5
5         10   12-May      6
6         20   12-May      7
7         30   12-May      8
8         40   12-May      9
9         50   12-May     10
10        10   13-May     11
11        20   13-May     12
12        30   13-May     13
13        40   13-May     14
14        50   13-May     15
15        10   14-May     16
16        20   14-May     17
17        30   14-May     18
18        40   14-May     19
19        50   14-May     20

其中,

In [1941]: dff
Out[1941]:
   11-May  12-May  13-May  14-May  Distance
0       1       6      11      16        10
1       2       7      12      17        20
2       3       8      13      18        30
3       4       9      14      19        40
4       5      10      15      20        50