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.
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]}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.