简体   繁体   English

如何使用没有索引的两列透视数据框

[英]How to pivot a dataframe with two columns with no index

I am trying to pivot my current two column dataframe which currently looks like this:我正在尝试旋转当前看起来像这样的当前两列数据框:

one   two
 a    12
 b    32
 c    12

I want to pivot this resulting in neither column becoming the index.我想旋转这导致两列都不成为索引。 My expected result is:我的预期结果是:

 a   b   c 
12  32  12

a, b, and c are the new columns. a、b 和 c 是新列。 12, 32, 12 are the values in the row. 12、32、12 是行中的值。

Thanks谢谢

Use set_index to move column 'one' into the index, then use T to transpose.使用set_index将列 'one' 移动到索引中,然后使用T进行转置。

a.set_index('one').T

Output:输出:

one   a   b   c
two  12  32  12

Info:信息:

<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

If this is your input:如果这是您的输入:

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

Then a.transpose() results in this:然后a.transpose()结果如下:

      0   1   2
one   a   b   c
two  12  32  12

Is this what you were looking for?这就是你要找的吗?

Giving everything the same index with .pivot_table使用.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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM