pandas 透视数据列到行和行到列

pandas pivot data Cols to rows and rows to cols

我正在使用 python 并且 pandas 尝试了多种尝试来调整以下内容(切换行和列)

示例: A 是唯一的

         A       B   C   D     E... (and so on)
     [0] apple   2   22  222
     [1] peach   3   33  333
     [N] ... and so on

我想看看

    ?  ?       ?     ?   ... and so on
    A  apple   peach
    B  2       3
    C  22      33
    D  222     333
    E 
    ... and so on

如果列以列“A”命名,我没问题,如果第一列需要一个名称,就叫它“名称”

    name  apple   peach ...
    B     2       3
    C     22      33
    D     222     333
    E 
    ... and so on

认为您想要 transpose 这里。

df = pd.DataFrame({'A': {0: 'apple', 1: 'peach'}, 'B': {0: 2, 1: 3}, 'C': {0: 22, 1: 33}})

df = df.T

print(df)

     0       1
A   apple   peach
B   2       3
C   22      33

编辑评论。我可能会重置索引,然后使用 df.columns 用列表更新列名。您可能希望在最后根据需要再次重置索引。

df.reset_index(inplace=True)

df.columns = ['name', 'apple', 'peach']

df = df.iloc[1:, :]

print(df)

    name    apple   peach
1   B       2       3
2   C       22      33

尝试 df.transpose() 它应该可以解决问题

采纳其他帖子的建议和一些其他调整(在线解释)对我有用。

    # get the key column that will become the column names.
    # add the column name for the existing columns

    cols = df['A'].tolist()
    cols.append('name')

    # Transform
    df = df.T
    
    # the transform takes the column, and makes it an index column.
    # need to add it back into the data set (you might want to drop 
    # the index later to get rid if it all together)
    df['name'] = df.index

    # now to rebuild the columns and move the new "name" column to the first col
    df.columns = cols
    cols = df.columns.tolist()
    cols = cols[-1:] + cols[:-1]
    df = df[cols]

    # remove the row, (was the column we used for the column names
    df = df.iloc[1:, :]