'How to add pandas series as a data into another series?
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?
Solution 1:[1]
Use s1.values to copy only data and not index
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Akash garg |
| Solution 2 |
