0

I have the following data structure (called df):

    x         Fx          Fxcum
0  -1.192809  0.888734    0.888734
1  -1.182809  0.483803    1.372537
2  -1.172809 -0.318153    1.054384
3  -1.162809 -0.966345    0.088038
4  -1.152809 -1.512387   -1.424349

The titles x, Fx, and Fxcum are dynamic. If I apply the function tolist():

dict(y=df['x'].tolist())

I get:

{'x': [-1.192809,
       -1.182809,
       -1.172809,
       -1.162809,
       -1.152809]}

First of all I need to read the titles that are not always x, Fx, and Fxcum and get the following list:

{'x': [-1.192809,
       -1.182809,
       -1.172809,
       -1.162809,
       -1.152809],
 'Fx': [-1.192809,
       -1.182809,
       -1.172809,
       -1.162809,
       -1.152809],
 'Fxcum': [-1.192809,
       -1.182809,
       -1.172809,
       -1.162809,
       -1.152809]}

Can you point me in the right direction. Do I need to create a loop or are there some libraries that can help me out?

martineau
  • 119,623
  • 25
  • 170
  • 301
Dino
  • 1,307
  • 2
  • 16
  • 47
  • 1
    I take it with df you're using python pandas? And you want to convert all columns `x`, `fx`, or `fxcum`? – Tony Apr 12 '18 at 15:41
  • 2
    if this is a pandas DataFrame, just do `df.to_dict()`. You can mess around with the `orient` parameter to get it in the form that you want. – Paul H Apr 12 '18 at 15:41
  • Hi Tony, yes I am using pandas. – Dino Apr 12 '18 at 15:45

1 Answers1

0

From your post, it seems like you are using Pandas.

Pandas has a method for doing exactly what you need: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_dict.html

df.to_dict('list')

Example:

>>> df
   col1  col2
a     1   0.1
b     2   0.2
>>> df.to_dict('list')
{'col1': [1, 2], 'col2': [0.5, 0.75]}
Danilo Gasques
  • 666
  • 6
  • 16