Loosing column names converting back to dataframe from list

Viewed 122

I have created a dataframe,i need to do two operations:

  1. Converting to a list
  2. converting the same list back to the dataframe with original column names.

Issue: i am loosing the column names when i first convert to a list and when i convert back to dataframe i am not getting those column names

Please help!

import pandas as pd
data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

#convert df to list
a=df.values.tolist()

#convert back to original dataframe
df1 = pd.DataFrame(a)
print(df1)

Current output

Current output without column names

i am unable to get column names

1 Answers

You need pass columns names by df.columns, also if not default index is necessary pass it too:

df1 = pd.DataFrame(a, columns=df.columns, index=df.index)

If default RangeIndex in original DataFrame:

df1 = pd.DataFrame(a, columns=df.columns)

EDIT:

If need some similar structure use DataFrame.to_dict with orient='split' there are converted DataFrame to dictionary of columnsnames, index and data like:

data = [['tom', 10], ['nick', 15], ['juli', 14]]
df = pd.DataFrame(data, columns = ['Name', 'Age'])

d = df.to_dict(orient='split')
print (d)
{'index': [0, 1, 2],
 'columns': ['Name', 'Age'], 
 'data': [['tom', 10], ['nick', 15], ['juli', 14]]}

And for original DataFrame use:

df2 = pd.DataFrame(d['data'], index=d['index'], columns=d['columns'])
print (df2)
   Name  Age
0   tom   10
1  nick   15
2  juli   14
Related