List to dataframe without any indexes or NaNs

Question:

I have a list of lists that I like to convert to a Pandas data frame.
My list looks like this:

[1 25
2 35
3 45
4 55
5 65
Name: a, Length: 5, dtype: int
6 75 
7 85
8 95
9 105
10 115
Name: b, Length: 5, dtype: int
11 125
12 135
13 145
14 155
15 165
Name: c, Length: 5, dtype: int]

My code to change it to a data frame is:

df = pd.DataFrame(list, index=None, columns=None)

the result looks like this:

enter image description here

But I want it to be like this:

enter image description here

Any help please?

Asked By: Totoro

||

Answers:

I think you have list of pandas series. Before creating a dataframe you have to remove the index/column info from each series. This can be simply done by mapping each series to list.

pd.DataFrame(map(list, lst))

Also don’t use list as your variable name since its a python’s builtin class.

Answered By: Shubham Sharma

Assuming that you have a list of series, you could reset the indices to make it so that the dataframe is constructed properly.

For instance, consider the following.

import pandas as pd

lst = [
    pd.Series([25,35,45,55,65], index = range(1,6)),
    pd.Series([75,85,95,105,115], index = range(6,11)),
    pd.Series([125,135,145,155,165], index = range(11,16))
]
result = pd.DataFrame([s.reset_index(drop = True) for s in lst])

The result:

     0    1    2    3    4
0   25   35   45   55   65
1   75   85   95  105  115
2  125  135  145  155  165

Also, if you’d prefer to have your columns 1-indexed instead of 0-indexed (as is the default), you can use the command

result = result.rename(columns = lambda x:x+1)
Answered By: Ben Grossmann
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.