Pandas将某些行转移到列

时间:2016-12-19 22:57:08

标签: pandas

我有以下pandas header

DataFrame

输出:

pandas.DataFrame({'C': {64: 128.0, 50: 32.0, 67: 128.0, 52: 32.0, 73: 512.0, 105: 32768.0, 42: 8.0, 47: 8.0, 76: 512.0, 79: 512.0}, 'gamma': {64: 0.0078125, 50: 3.0517578125e-05, 67: 0.5, 52: 0.00048828125, 73: 0.001953125, 105: 0.03125, 42: 0.00048828125, 47: 0.5, 76: 0.125, 79: 8.0}, 'kernel': {64: 'rbf', 50: 'rbf', 67: 'rbf', 52: 'rbf', 73: 'rbf', 105: 'rbf', 42: 'rbf', 47: 'rbf', 76: 'rbf', 79: 'rbf'}, 'std.dev': {64: 0.0063099999999999996, 50: 0.0077600000000000004, 67: 0.0071300000000000001, 52: 0.0066800000000000002, 73: 0.00611, 105: 0.0056100000000000004, 42: 0.0075399999999999998, 47: 0.0058100000000000001, 76: 0.0070000000000000001, 79: 0.0048799999999999998}, 'mean': {64: 0.97031000000000001, 50: 0.94882999999999995, 67: 0.96369000000000005, 52: 0.96518000000000004, 73: 0.96897999999999995, 105: 0.96455000000000002, 42: 0.96267999999999998, 47: 0.96825000000000006, 76: 0.96601999999999999, 79: 0.96560000000000001}})

我需要将其转换为C列仅包含C的唯一值的格式,并且gamma列中的每个唯一值都将成为新列。对于每个这样的新伽马列,我想显示相应的C和gamma值的均值和std.dev。

2 个答案:

答案 0 :(得分:2)

为了完整起见,您可以直接使用pivot_table

df.pivot_table(index='C', 
               columns='gamma', 
               values=['mean','std.dev'])\
  .swaplevel(0, 1, axis=1)\
  .sort_index(level=0, axis=1)

答案 1 :(得分:1)

使用set_indexunstack

df.set_index(['C', 'gamma'])[['mean', 'std.dev']].unstack().swaplevel(0, 1, 1).sort_index(1)

enter image description here

或等同于pivot

pd.concat(
    [df.pivot(index='C', columns='gamma', values=c) for c in ['mean', 'std.dev']],
     keys=['mean', 'std.dev']
).unstack(0)