Home > Software design >  Creating dictionary from dataframe with columns as values python
Creating dictionary from dataframe with columns as values python

Time:08-29

I am trying to create a dictionary from a dataframe.

from pandas import util
df= util.testing.makeDataFrame()
df.index.name = 'name'

        A   B   C   D
name                
qSfQX3rj48  0.184091    -1.195861   0.998988    -0.970523
KSYYLUGiJB  -0.998997   -0.387378   -0.303704   0.833731
PmsVVmRbQX  -1.510940   -1.062814   0.934954    0.970467
oHjAqjAv1P  -1.366054   0.595680    -1.039310   -0.126625
a1cU5c4psT  -0.486282   -0.369012   -0.284495   -1.263010
qnqmltdFGR  -0.041243   -0.792538   0.234809    0.894919


df.to_dict() 


{'A': {'qSfQX3rj48': 0.1840905950693832,
  'KSYYLUGiJB': -0.9989969426889559,
  'PmsVVmRbQX': -1.5109402125881068,
  'oHjAqjAv1P': -1.3660539127241154,
  'a1cU5c4psT': -0.48628192605203563,
  'qnqmltdFGR': -0.04124312561281138,

The above dict method is using the column name as keys.

dict_keys(['A', 'B', 'C', 'D'])

How can I can set it to a dict where the columns A B C D are the values for the name column. Thus it will have just 1 key.

    A   B   C   D
name                
qSfQX3rj48  0.184091    -1.195861   0.998988    -0.970523

Should produce a dictionary with a list of values.

 {'qSfQX3rj48': [0.184091, -1.195861, 0.998988, -0.970523],
 'KSYYLUGiJB': [-0.998997, -0.387378 , -0.303704, 0.833731],

And values are column, thus:

{'name': [A, B, C, D],

CodePudding user response:

d = df.T.to_dict('list')
d[df.index.name] = df.columns.tolist()

 

Example

df = pd.DataFrame(np.arange(12).reshape(3, 4), 
                  columns=['A', 'B', 'C', 'D'],
                  index=['one', 'two', 'three'])
df.index.name = 'name'

df:

       A  B   C   D
name               
one    0  1   2   3
two    4  5   6   7
three  8  9  10  11

d:

{'one': [0, 1, 2, 3],
 'two': [4, 5, 6, 7],
 'three': [8, 9, 10, 11],
 'name': ['A', 'B', 'C', 'D']}

CodePudding user response:

Code:

dict([(nm,[a,b,c,d ]) for nm, a,b,c,d in zip(df.index, df.A, df.B, df.C, df.D)])
  • Related