I would like to convert a the dataframe like below (where ix is the index of the dataframe)
ix | A | B |
---|---|---|
X | 0 | 0 |
Y | 0 | 0 |
to a list of lists like so:
[ [ix, A, B], [X, 0, 0], [Y, 0, 0] ]
to create a matrix (list of lists) that still contains the dataframe column and index names, A, B and X, Y respectively.
CodePudding user response:
Convert columns
to list and append the body
list:
[df.columns.tolist()] df.values.tolist()
[['ix', 'A', 'B'], ['X', 0, 0], ['Y', 0, 0]]
Or if you meant to just store this somewhere for reproducibility, you might want to use to_dict
method:
df.to_dict('list')
{'ix': ['X', 'Y'], 'A': [0, 0], 'B': [0, 0]}
CodePudding user response:
If all your columns are the same type, I would use .to_numpy
and then add the columns to the array using something like:
a = df.to_numpy()
a = numpy.vstack([df.columns, a])
This involves more imports (technically), but you're already importing pandas so numpy isn't much else to bring in.