Nested List To Pandas Dataframe With Headers
Basically I am trying to do the opposite of How to generate a list from a pandas DataFrame with the column name and column values? To borrow that example, I want to go from the for
Solution 1:
One way to do this would be to take the column names as a separate list and then only give from 1st index for pd.DataFrame
-
In [8]: data = [['Name','Rank','Complete'],
...: ['one', 1, 1],
...: ['two', 2, 1],
...: ['three', 3, 1],
...: ['four', 4, 1],
...: ['five', 5, 1]]
In [10]: df = pd.DataFrame(data[1:],columns=data[0])
In [11]: df
Out[11]:
Name Rank Complete
0 one 111 two 212 three 313 four 414 five 51
If you want to set the first column Name
column as index, use the .set_index()
method and send in the column to use for index. Example -
In [16]: df = pd.DataFrame(data[1:],columns=data[0]).set_index('Name')
In [17]: df
Out[17]:
Rank Complete
Name
one 11
two 21
three 31
four 41
five 51
Post a Comment for "Nested List To Pandas Dataframe With Headers"