Home > Enterprise >  How to convert columns and values of DataFrame to one list?
How to convert columns and values of DataFrame to one list?

Time:08-31

I need to convert DataFrame to a list with saving its headers as the first item in the list. I guess one of the ways is to convert columns and values separately and then join these lists. But is there a better way?

dataframe,

import pandas as pd
df=pd.DataFrame({"Sales QTY":[10,20,30,40],
                 "Sales Person":['Jack', 'Adam', 'Ken', 'Jack'],
                 "Product":["Apple", "Orange","Apple","Cherry"]
                 })

desired output

[['Sales QTY', 'Sales Person', 'Product'],
  [10, 'Jack', 'Apple'],
 [20, 'Adam', 'Orange'],
 [30, 'Ken', 'Apple'],
 [40, 'Jack', 'Cherry']]

CodePudding user response:

lst = df.to_numpy().tolist()
lst.insert(0, df.columns.tolist())

lst
[['Sales QTY', 'Sales Person', 'Product'],
 [10, 'Jack', 'Apple'],
 [20, 'Adam', 'Orange'],
 [30, 'Ken', 'Apple'],
 [40, 'Jack', 'Cherry']]

CodePudding user response:

pd.concat([df.columns.to_frame().T, df], ignore_index=True).values.tolist()

[['Sales QTY', 'Sales Person', 'Product'],
 [10, 'Jack', 'Apple'],
 [20, 'Adam', 'Orange'],
 [30, 'Ken', 'Apple'],
 [40, 'Jack', 'Cherry']]
  • Related