-2

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],
Slartibartfast
  • 1,058
  • 4
  • 26
  • 60
  • 2
    Could you provide the expected output ? – rochard4u Aug 29 '22 at 07:56
  • 2
    It's not quite clear what you mean, but maybe you want `df.to_dict(orient="list")`? – fsimonjetz Aug 29 '22 at 07:59
  • I have updated the question with expected dictionary – Slartibartfast Aug 29 '22 at 08:01
  • note that `df.index.name` sets the name of the index for _**rows**_. If you want to set the name of the index for _columns_ instead, you can set `df.columns.name`. The general method for this is [`.rename_axis`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rename_axis.html): `df.rename_axis(columns='col_index')` – Vladimir Fokow Aug 29 '22 at 08:20

2 Answers2

3
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']}
Vladimir Fokow
  • 3,728
  • 2
  • 5
  • 27
-1

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)])
R. Baraiya
  • 1,490
  • 1
  • 4
  • 17
  • 4
    For further guidance you can check: https://stackoverflow.com/questions/26716616/convert-a-pandas-dataframe-to-a-dictionary – R. Baraiya Aug 29 '22 at 08:09