Home > Back-end >  Creating a DataFrame from a dictionary of Series results in lost indices and NaNs
Creating a DataFrame from a dictionary of Series results in lost indices and NaNs

Time:11-11

dict_with_series = {'Even':pd.Series([2,4,6,8,10]),'Odd':pd.Series([1,3,5,7,9])}  

Data_frame_using_dic_Series = pd.DataFrame(dict_with_series)

# Data_frame_using_dic_Series = pd.DataFrame(dict_with_series,index=\[1,2,3,4,5\]), gives a NaN value I dont know why

display(Data_frame_using_dic_Series)

I tried labeling the index but when i did it eliminates the first column and row instead it prints extra column and row at the bottom with NaN value. Can anyone explain me why is it behaving like this , have I done something wrong If I don't use the index labeling argument it works fine

CodePudding user response:

When you run:

Data_frame_using_dic_Series = pd.DataFrame(dict_with_series,index=[1,2,3,4,5])

You request to only use the indices 1-5 from the provided Series, but the original indexing of a Series is from 0, thus resulting in a reindexing.

If you want to change the index, do it afterwards:

Data_frame_using_dic_Series = (pd.DataFrame(dict_with_series)
                                 .set_axis([1, 2, 3, 4, 5])
                               )

Output:

   Even  Odd
1     2    1
2     4    3
3     6    5
4     8    7
5    10    9
  • Related