簡體   English   中英

pandas DataFrame通過多個列值重新整形

[英]pandas DataFrame reshape by multiple column values

我試圖讓自己擺脫JMP進行數據分析,但無法確定相當於JMP的Split Columns函數的pandas。 我從以下DataFrame開始:

In [1]: df = pd.DataFrame({'Level0': [0,0,0,0,0,0,1,1,1,1,1,1], 'Level1': [0,1,0,1,0,1,0,1,0,1,0,1], 'Vals': [1,3,2,4,1,6,7,5,3,3,2,8]})
In [2]: df
Out[2]:
    Level0  Level1  Vals
0        0       0     1
1        0       1     3
2        0       0     2
3        0       1     4
4        0       0     1
5        0       1     6
6        1       0     7
7        1       1     5
8        1       0     3
9        1       1     3
10       1       0     2
11       1       1     8

我可以使用pivot_table函數處理JMP函數的一些輸出場景,但是我pivot_table Vals列被Level0Level1的唯一組合拆分以提供以下輸出:

Level0   0       1
Level1   0   1   0   1
0        1   3   7   5
1        2   4   3   3
2        1   6   2   8

我嘗試了pd.pivot_table(df, values='Vals', columns=['Level0', 'Level1'])但這給出了不同組合的平均值:

Level0  Level1
0       0         1.333333
        1         4.333333
1       0         4.000000
        1         5.333333

我也嘗試過pd.pivot_table(df, values='Vals', index=df.index, columns=['Level0', 'Level1']這會得到我想要的列標題,但不起作用,因為它會強制輸出與原始行具有相同的行數,因此輸出具有大量NaN值:

Level0   0       1
Level1   0   1   0   1
0        1 NaN NaN NaN
1      NaN   3 NaN NaN
2        2 NaN NaN NaN
3      NaN   4 NaN NaN
4        1 NaN NaN NaN
5      NaN   6 NaN NaN
6      NaN NaN   7 NaN
7      NaN NaN NaN   5
8      NaN NaN   3 NaN
9      NaN NaN NaN   3
10     NaN NaN   2 NaN
11     NaN NaN NaN   8

有什么建議?

這是一個解決方法,但你可以這樣做:

df.pivot_table(index=df.groupby(['Level0', 'Level1']).cumcount(), 
               columns=['Level0', 'Level1'], values='Vals', aggfunc='first')
Out: 
Level0  0     1   
Level1  0  1  0  1
0       1  3  7  5
1       2  4  3  3
2       1  6  2  8

這里的想法是原始DataFrame中的輸出索引不容易獲得。 您可以通過以下方式獲得它:

df.groupby(['Level0', 'Level1']).cumcount()
Out: 
0     0
1     0
2     1
3     1
4     2
5     2
6     0
7     0
8     1
9     1
10    2
11    2
dtype: int64

現在,如果您將此作為pivot_table的索引pivot_table ,則任意aggfunc (mean,min,max,first或last)應該適用於您,因為這些索引列對只有一個條目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM