2

I have a df:

  x
0 a
1 b
2 c
0 a
1 b
2 c
0 a
1 b
2 c

How can I turn those duplicated index values to new rows? Desired output:

  x  y  z
0 a  a  a
1 b  b  b
2 c  c  c

I have been trying to add new columns to a dataframe through a loop with append, but it just keeps giving me this output by adding rows instead of columns. I tried join but that didn't work either, so i figured there must just be a hacky way to turn these repreated index values to new columns.

bismo
  • 1,257
  • 1
  • 16
  • 36

2 Answers2

1
print(df.groupby(level=0).agg(list)["x"].apply(pd.Series))

Prints:

   0  1  2
0  a  a  a
1  b  b  b
2  c  c  c

To rename columns:

print(
    df.groupby(level=0)
    .agg(list)["x"]
    .apply(pd.Series)
    .rename(columns={0: "x", 1: "y", 2: "z"})
)

Prints:

   x  y  z
0  a  a  a
1  b  b  b
2  c  c  c
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1
#change column name as required.
new_df = pd.DataFrame(df.groupby(df.index).values.apply(list).to_list())
Nk03
  • 14,699
  • 2
  • 8
  • 22