Home > Software engineering >  Keys as Rows (Pandas Dataframe from dictionary)
Keys as Rows (Pandas Dataframe from dictionary)

Time:12-05

I have this dictionary:

d = {'a': (1,2,3), 'b': (4,5,6)}

I would like it to be formed as a dataframe where the key is shown as row along with its corresponding values, like the table below:

Keys Values
a 1
a 2
a 3
b 4
b 5

Any ideas?

CodePudding user response:

d = {'a': (1,2,3), 'b': (4,5,6)}
df = pd.DataFrame(d).unstack().droplevel(1).reset_index().rename({'index':'Keys', 0:'Values'}, axis=1)

Output:

>>> df
  Keys  Values
0    a       1
1    a       2
2    a       3
3    b       4
4    b       5
5    b       6

CodePudding user response:

Here is my suggestion.

  1. Create your dataframe with the following command:

df = pd.DataFrame({'Keys': list(dict.keys()), 'Values': list(dict.values())})

  1. Explode your dataframe on column of 'Values' with the following command:

df = df.explode(column='Values').reset_index(drop=True

The output result is something like this:

       Keys   Values
  0    a      1
  1    a      2
  2    a      3
  3    b      4
  4    b      5
  5    b      6

CodePudding user response:

You can unstack the dataframe, reset_index and change column names:

df = (pd.DataFrame(dictionary)
      .unstack()
      .reset_index()
      .loc[:,['level_0',0]]
      .rename(columns={'level_0':'keys',0:'values'}))

Output:

  keys  values
0    a       1
1    a       2
2    a       3
3    b       4
4    b       5
5    b       6
  • Related