Pandas df.pivot()和pd.pivot_table()具有多个索引

时间:2017-03-01 03:00:34

标签: python pandas

我正在尝试将带有多个索引的长格式df转换为宽格式df。为什么df_in.pivot()失败和/或为什么pd.pivot_table返回带有奇怪层次结构索引的结果以便我无法访问我想要投射的列?

# input table
df_in = pd.DataFrame({'idx1':range(2)*4, 'idx2':['a']*4+['b']*4, 'field': ['f1']*2+['f2']*2+['f1']*2+['f2']*2, 'value': np.array(range(2)*4)*2+1})
'''
  field  idx1 idx2  value
0    f1     0    a      1
1    f1     1    a      3
2    f2     0    a      1
3    f2     1    a      3
4    f1     0    b      1
5    f1     1    b      3
6    f2     0    b      1
7    f2     1    b      3
'''

# want something like this
pd.DataFrame({'idx1':range(2)*2, 'idx2': ['a']*2+['b']*2, 'a':[1,3]*2, 'b':[1,3]*2})
'''
   a  b  idx1 idx2
0  1  1     0    a
1  3  3     1    a
2  1  1     0    b
3  3  3     1    b
'''

#doesn't work => ValueError: all arrays must be same length
df_in.pivot(index=['idx1','idx2'], columns =['field'])

#doesn't work => weird hierarchical index
pd.pivot_table(df_in, index=['idx1','idx2'], columns =['field'])

'''
          value   
field        f1 f2
idx1 idx2         
0    a        1  1
     b        1  1
1    a        3  3
     b        3  3
'''
# doesn't work => KeyError: 'f1'
pd.pivot_table(df_in, index=['idx1','idx2'], columns =['field'])['f1']

# doesn't work => KeyError: 'f1'
pd.pivot_table(df_in, index=['idx1','idx2'], columns =['field']).reset_index()['f1']

1 个答案:

答案 0 :(得分:2)

要避免使用多级列,请将值列显式指定为字符串而不是列表就足够了:

df_out = df_in.pivot_table(values=['value'], index=['idx1', 'idx2'], columns='field')

如果您有多级列,则可以使用元组来访问它们,例如:

f1

给出一个包含多级列的数据框,要访问df_out[('value', 'f1')] 列,您可以这样做:

#idx1  idx2
#0     a       1
#      b       1
#1     a       3
#      b       3
#Name: (value, f1), dtype: int64

给出:

try {
    $conn = new PDO("mysql:host=$server;dbname=$dbName", $serverUser, $serverPass);
    $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $pdoErr) {
    echo "Database Error: ".$pdoErr->getMessage();
} catch (Exception $err) {
    echo "Error: ".$err->getMessage();
}

$editQuery = $conn -> prepare("INSERT INTO `users`(`column1`, `column2`, `column3`) VALUES (:value1, :value2, :value3)";
$editQuery -> execute(array('value1' => $value1, 'value2' => $value2, 'value3' => $value3));