Home > Enterprise >  spread key-values across multiple columns with python
spread key-values across multiple columns with python

Time:05-26

I'm trying to transpose df into df_spread.

import pandas

df = {"Type": ("A", "B", "B", "C","D"),
      "Amount":(220, 68, 1400, 120, 99)
}

df = pandas.DataFrame(df)

The output I want would be like this:

df_spread =  {"A": 220, "B": 68, "B": 1400, "C": 120, "D": 99
}

df_spread = pandas.DataFrame(df_spread)

I know that a wide dataframe like this isn't the best practice, but I'm going to concatenate df with a bunch of other dataframes.

CodePudding user response:

IIUC, you can

>>> df.set_index('Type').T
Type      A   B     B    C   D
Amount  220  68  1400  120  99

(Possibly followed by some index renaming, but if you're going to concatenate with other dfs, chances are you'll probably ignore the index anyway.)

CodePudding user response:

You can do:

df_out = pd.DataFrame(df['Amount']).T
df_out.columns = df['Type']

Output:

      A    B    B   C   D
0   220   68 1400 120  99
  • Related