Python Pandas 两列的透视(ColumnName 和 Value)

Pau*_*son 5 python pivot dataframe pandas

我有一个 Panda 数据框,其中包含两列以及一个默认索引。第一列是预期的“列名称”,第二列是该列所需的值。

    name            returnattribute
0   Customer Name   Customer One Name
1   Customer Code   CGLOSPA
2   Customer Name   Customer Two Name
3   Customer Code   COTHABA
4   Customer Name   Customer Three Name
5   Customer Code   CGLOADS
6   Customer Name   Customer Four Name
7   Customer Code   CAPRCANBRA
8   Customer Name   Customer Five Name
9   Customer Code   COTHAMO
Run Code Online (Sandbox Code Playgroud)

我想指出这一点,以便我有 5 行两列(“客户名称”和“客户代码”),而不是 10 行。希望的结果如下:

    Customer Code   Customer Name
0   CGLOSPA         Customer One Name
1   COTHABA         Customer Two Name
2   CGLOADS         Customer Three Name
3   CAPRCANBRA      Customer Four Name
4   COTHAMO         Customer Five Name
Run Code Online (Sandbox Code Playgroud)

我尝试使用 pandas 枢轴功能:

df.pivot(columns='name', values='returnattribute')
Run Code Online (Sandbox Code Playgroud)

但这会导致十行仍然有交替的空白:

    Customer Code   Customer Name
0   NaN             Customer One Name
1   CGLOSPA         NaN
2   NaN             Customer Two Name
3   COTHABA         NaN
4   NaN             Customer Three Name
5   CGLOADS         NaN
6   NaN             Customer Four Name
7   CAPRCANBRA      NaN
8   NaN             Customer Five Name
9   COTHAMO         NaN
Run Code Online (Sandbox Code Playgroud)

如何旋转数据框以获得 5 行两列?

moz*_*way 2

您还可以直接将新索引传递给pivot_table, 使用,aggfunc='first'因为您有非数字数据:

df.pivot_table(index=df.index//2, columns='name',
               values='returnattribute', aggfunc='first')
Run Code Online (Sandbox Code Playgroud)

输出:

name Customer Code        Customer Name
0          CGLOSPA    Customer One Name
1          COTHABA    Customer Two Name
2          CGLOADS  Customer Three Name
3       CAPRCANBRA   Customer Four Name
4          COTHAMO   Customer Five Name
Run Code Online (Sandbox Code Playgroud)