0

Have a simple df:

df = pd.DataFrame({"v": [1, 2]}, index = pd.Index(data = ["a", "b"], name="colname"))

Want to reshape it to look like this:

  a b
0 1 2

How do I do that? I looked at the docs for pd.pivot and pd.pivot_table but

df.reset_index().pivot(columns = "colname", values = "v")

produces a df that has NaNs obviously.

update: i want dataframes not series because i am going to concatenate a bunch of them together to store results of a computation.

Alex
  • 1,281
  • 1
  • 13
  • 26

2 Answers2

2

How about:

df.T.reset_index(drop=True)

[out]

colname  a  b
0        1  2
Chris Adams
  • 18,389
  • 4
  • 22
  • 39
2

From your setup

        v
colname 
a       1
b       2

Seems like you need to transpose

>>> df.T

or

>>> df.transpose()

Which yield

colname a   b
v       1   2

You can always reset the index to get 0 and set the column name to None to get your expected output

ndf = df.T.reset_index(drop=True)
ndf.columns.name = None

    a   b
0   1   2
rafaelc
  • 57,686
  • 15
  • 58
  • 82