python - pandas DataFrame 按多个列值 reshape

标签 python pandas

我正试图摆脱 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 函数的一些输出场景,但我对 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 的索引传递,则任意 aggfunc(平均值、最小值、最大值、第一个或最后一个)应该可以作为这些索引为您工作- 列对只有一个条目。

关于python - pandas DataFrame 按多个列值 reshape ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41078009/

相关文章:

python - (numpy) __array_wrap__ 做什么?

python - for 循环中的 pandas isin 函数

python - 稀疏矩阵可以与 MultinomialNB 一起使用吗?

python - 使用 ctypes 从 .dll 中的 python 中的 C++ 函数 - 找不到函数和访问冲突

python-3.x - 在 python 中更改多边形坐标的 long,lat 值

python - 有没有更有效的方法将映射应用于 pandas 系列?

python - 在单个字符串中打印 pandas 行(jupyter 笔记本)

python - 有条件地删除重复项 pandas python

python字典到csv文件

python - 将图像插入 pdf 文件