简体   繁体   中英

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. 12, 32, 12 are the values in the row.

Thanks

Use set_index to move column 'one' into the index, then use T to transpose.

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:

      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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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