Pandas | Series constructor
Start your free 7-days trial now!
Pandas Series(~) constructor initialises a new Series.
Parameters
1. data | array-like or iterable or dict or scalar
The data to initialise the Series with.
2. indexlink | 1D array-like or index | optional
The index to use for the Series. The index does not have to be unique, that is, ["a","b","a"] is allowed.
3. dtypelink | string or numpy.dtype or ExtensionDtype | optional
The data type of the Series. By default, the data type is inferred from data.
4. namelink | string | optional
The name to assign to the Series.
5. copylink | boolean | optional
If
True, then a new Series would be returned. Modifying this Series would not mutate the originaldataand vice versa.If
False, then the returned Series uses the same block of memory occupied bydata. This means that modifying the Series would mutate the originaldataand vice versa.
copy=False only takes effect if data is a Numpy array or another Series. By default, copy=True.
Return Value
A Series object.
Examples
Using an array
To initialise a Series using an array:
s = pd.Series([3,4,5])s
0 31 42 5dtype: int64
Since we did not specify index, the default integer index was used ([0,1,2]).
Using a dictionary
To initialise a Series using a map:
my_data = {"A":3, "B":4, "C":5}s = pd.Series(my_data)s
A 3B 4C 5dtype: int64
Here, notice how the key of the dictionary became the index of the Series.
Specifying index
To set the index of the Series, pass in the index parameter:
s = pd.Series([3,4,5], index=["A","B","C"])s
A 3B 4C 5dtype: int64
Specifying dtype
To enforce a data type on the Series:
s = pd.Series(["3","4","5"], dtype="int")s
0 31 42 5dtype: int64
Specifying name
To assign a name to the Series, pass in the name parameter:
s = pd.Series([3,4,5], name="my_series")s
0 31 42 5Name: my_series, dtype: int64
Specifying copy
By default, copy=True, which means that a new block of memory is allocated for the constructed Series. Modifying this Series will therefore not mutate the original data and vice versa.
Instead of creating a new copy of data, we can initialise a Series that uses the same memory block occupied by data:
s1 = pd.Series([3,4])s2 = pd.Series(s1, copy=False)s2
0 31 4dtype: int64
Here, we are initialising a Series s2 from Series s1. The key is that these Series share the same block of memory for their data, which means that modifying one would mutate the other:
s1[0] = 9s2
0 91 4dtype: int64