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:
But I want it to be like this:
Any help please?
>Solution :
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)