Home > Mobile >  How to add pandas series as a data into another series?
How to add pandas series as a data into another series?

Time:04-18

In this code :

import pandas as pd
arr=list(range(10))
s1=pd.Series(arr)
s2=pd.Series(s1,index=arr)
print(s2)

the result of print(s1) is this:

0    0
1    1
2    2
3    3
4    4
5    5
6    6
7    7
8    8
9    9
dtype: int64

I added s1 as a data to s2 and i specified the index for s2 like this:

s2=pd.Series(s1,index=arr)

But the result of print (s2) is the same as print (s1). Then why s2 does not have index and data of s1 as a data for itself?

CodePudding user response:

Use s1.values to copy only data and not index

CodePudding user response:

The reason is that when you create a Series from a list, the index is created by default from 0 to n-1, where n is the number of elements in the list.

When you create a Series from another Series, the index is inherited from the original Series unless you specify a new index.

You can create a MultiIndex (hierarchical index) object using

pd.MultiIndex

For more information, you can take a look at the documentation https://pandas.pydata.org/docs/user_guide/advanced.html

  • Related