1

I have a dict as follows:

data_dict = {'1.160.139.117': ['712907','742068'],
 '1.161.135.205': ['667386','742068'],
 '1.162.51.21': ['326136', '663056', '742068']}

I want to convert the dict into a dataframe:

df= pd.DataFrame.from_dict(data_dict, orient='index')

enter image description here

How can I create a dataframe that has columns representing the values of the dictionary and rows representing the keys of the dictionary?, as below: enter image description here

1 Answer 1

3

The best option is #4

pd.get_dummies(df.stack()).sum(level=0)

Option 1:

One way you could do it:

df.stack().reset_index(level=1)\
  .set_index(0,append=True)['level_1']\
  .unstack().notnull().mul(1)

Output:

               326136  663056  667386  712907  742068
1.160.139.117       0       0       0       1       1
1.161.135.205       0       0       1       0       1
1.162.51.21         1       1       0       0       1

Option 2

Or with a litte reshaping and pd.crosstab:

df2 = df.stack().reset_index(name='Values')
pd.crosstab(df2.level_0,df2.Values)

Output:

Values         326136  663056  667386  712907  742068
level_0                                              
1.160.139.117       0       0       0       1       1
1.161.135.205       0       0       1       0       1
1.162.51.21         1       1       0       0       1

Option 3

df.stack().reset_index(name="Values")\
  .pivot(index='level_0',columns='Values')['level_1']\
  .notnull().astype(int)

Output:

Values         326136  663056  667386  712907  742068
level_0                                              
1.160.139.117       0       0       0       1       1
1.161.135.205       0       0       1       0       1
1.162.51.21         1       1       0       0       1

Option 4 (@Wen pointed out a short solution and fastest so far)

pd.get_dummies(df.stack()).sum(level=0)

Output:

               326136  663056  667386  712907  742068
1.160.139.117       0       0       0       1       1
1.161.135.205       0       0       1       0       1
1.162.51.21         1       1       0       0       1
Sign up to request clarification or add additional context in comments.

3 Comments

maybe pd.get_dummies(df.stack()).sum(level=0) :-)
Please do it, my friend :-) and happy thanksgiving
@wen Happy T-day to you too!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.