Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
Pandas DataFrame to lists of lists including headers

Say I have a DataFrame that looks like this:

df = pd.DataFrame([[1, 2, 3], 
                   [4, 5, 6], 
                   [7, 8, 9]], 
                   columns=['Col 1', 'Col 2', 'Col 3'])
>>> df
   Col 1  Col 2  Col 3
0      1      2      3
1      4      5      6
2      7      8      9

Is there a Pandas way of returning the DataFrame as a list of lists with the headers included?

I can return the headers and values as lists as follows

>>> df.columns.values.tolist()
['Col 1', 'Col 2', 'Col 3']
>>> df.values.tolist()
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> df.tolist()

But how could I return the following result?

[['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use double transpose with reset_index:

print (df.T.reset_index().values.T.tolist())
[['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

Or nicer insert:

a = df.columns.values.tolist()
b = df.values.tolist()

b.insert(0, a)
print (b)
[['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
over 4 years ago · Santiago Trujillo Report

0

You have two lists, so using:

[df.columns.values.tolist()] + df.values.tolist()
>>> [['Col 1', 'Col 2', 'Col 3'], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!