0

I have a dataframe with date as index and columns col1, col2, col3, col4. I wanna convert the dataframe to a list of lists with each sub-list in the format [[values of col1], [values of col2],[]]. Also can I set the index of the sub-lists as the date which is index of the dataframe.

I used list(df.values) but the values are of type object.

[array([datetime.date(2022, 7, 17), '\xa0808.936279', '\xa097.621918',
        '\xa01391.144531', '\xa04.924944'], dtype=object),
 array([datetime.date(2022, 7, 24), '\xa0843.818848', '\xa092.959511',
        '\xa01355.005371', '\xa07.948269'], dtype=object),
 array([datetime.date(2022, 7, 31), '\xa0754.019470', '\xa094.230988',
        '\xa01291.539917', '\xa07.841336'], dtype=object),
 array([datetime.date(2022, 8, 7), '\xa0815.897095', '\xa082.941071',
        '\xa01352.416260', '\xa06.506207'], dtype=object),
 array([datetime.date(2022, 8, 14), '\xa0840.138611', '\xa087.004288',
        '\xa01383.613281', '\xa04.411084'], dtype=object),
 array([datetime.date(2022, 8, 21), '\xa0840.067810', '\xa097.822212',
        '\xa01428.549316', '\xa07.653486'], dtype=object),
 array([datetime.date(2022, 8, 28), '\xa0904.777649', '\xa096.018684',
        '\xa01327.484497', '\xa06.799400'], dtype=object),
 array([datetime.date(2022, 9, 4), '\xa0824.618164', '\xa097.722969',
        '\xa01291.173096', '\xa03.542029'], dtype=object)]
Samuel
  • 29
  • 3

1 Answers1

0

Assuming you have a Pandas DataFrame, use the .to_dict() method and set orient="column"

https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_dict.html#pandas.DataFrame.to_dict

>>> df = pd.DataFrame({'a':[1,2,3],'b':[1,2,3]})
>>> df.to_dict(orient="list")
{'a': [1, 2, 3], 'b': [1, 2, 3]}
>>> list(df.to_dict(orient="list").values())
[[1, 2, 3], [1, 2, 3]]

You could also unpack into .values() and call .tolist() on each Series, but it might be less useful to you in general than the dict

>>> [l.tolist() for l in df.values]
[[1, 1], [2, 2], [3, 3]]
>>> [l.tolist() for l in df.T.values]  # transpose
[[1, 2, 3], [1, 2, 3]]
ti7
  • 16,375
  • 6
  • 40
  • 68
  • Can I set a custom index for the list inside main list? – Samuel Nov 17 '22 at 10:36
  • hmm.. what would that custom index be? I'd just [add it as a column](https://stackoverflow.com/a/20461206/4541045) if that's all you're after - also I see from your tags you might actually be working with Microsoft Excel, just trying to coerce your DataFrame into a spreadsheet and suffering with an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)! Pandas actually provides a dedicated method for writing to the format https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_excel.html – ti7 Nov 17 '22 at 14:30