Dim Tsi
Dim Tsi

Reputation: 25

Keys as Rows (Pandas Dataframe from dictionary)

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?

Upvotes: 2

Views: 2474

Answers (2)

Mohammadreza Riahi
Mohammadreza Riahi

Reputation: 602

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

Upvotes: 3

user17242583
user17242583

Reputation:

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

Upvotes: 2

Related Questions