如何使用没有索引的两列来旋转数据框

问题描述 投票:3回答:3

我正在尝试调整当前的两列数据框,目前看起来像这样:

one   two
 a    12
 b    32
 c    12

我想透视它,导致两列都不成为索引。我的预期结果是:

 a   b   c 
12  32  12

a,b和c是新列。 12,32,12是行中的值。

谢谢

python pandas
3个回答
4
投票

使用set_index将列'one'移动到索引中,然后使用T进行转置。

a.set_index('one').T

输出:

one   a   b   c
two  12  32  12

信息:

<class 'pandas.core.frame.DataFrame'>
Index: 1 entries, two to two
Data columns (total 3 columns):
a    1 non-null int64
b    1 non-null int64
c    1 non-null int64
dtypes: int64(3)
memory usage: 28.0+ bytes
None

3
投票

如果这是您的输入:

a = pd.DataFrame([("a", 12), ("b", 32), ("c", 12)], columns=["one", "two"])
  one  two
0   a   12
1   b   32
2   c   12

然后a.transpose()导致这个:

      0   1   2
one   a   b   c
two  12  32  12

这是你在找什么?


0
投票

使用.pivot_table为所有内容提供相同的索引

df.pivot_table(columns='one', index=df.index//len(df), values='two').rename_axis(None, axis=1)

#or with pivot
df = df.pivot(columns='one', index=df.index//len(df)).rename_axis([None, None], axis=1)
df.columns = [y for _,y in df.columns]

    a   b   c
0  12  32  12
© www.soinside.com 2019 - 2024. All rights reserved.