0

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?

Totoro
  • 474
  • 2
  • 6
  • 18
  • 4
    Could you please clarify the exact structure of your list? It would be ideal if you could paste it in a way that allows us to reproduce your result. – Ben Grossmann Mar 14 '23 at 16:20

2 Answers2

2

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.

Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53
2

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)
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
  • 2
    @Chrysophylaxs Fixed my answer, thanks for catching that mistake – Ben Grossmann Mar 14 '23 at 16:35
  • Thank you very much, it works as I wished. Could I use reset_index function for dropping the rows' names too ('a', 'b', 'c' in my original example)? – Totoro Mar 14 '23 at 16:53
  • 1
    @Totoro No, dataframes will always have index (row-label) and this will be displayed by default. You can [print dataframes out without their index](https://stackoverflow.com/q/24644656/2476977), though. – Ben Grossmann Mar 14 '23 at 18:48