Pandas pd.Series() function
pd.Series() is a core function in the Pandas library for creating a one-dimensional array (similar to a list or NumPy array), but it is more powerful than a plain array.Series It can store any data type (such as integers, strings, floats, etc.), and each element has an associated index, which makes data manipulation more flexible.
Basic syntax of pd.Series()
pd.Series(data, index=None, dtype=None, name=None, copy=False)
Parameter Description:
- data: data, which can be a list, dictionary, NumPy array, etc.
- index: index, used to label the data. If omitted, it defaults to starting at 0.
- dtype: data type, such as
int、float、str, etc. - name: the name of the Series, usually used to label the data.
- copy: whether to copy the data, defaults to
False。
How to use pd.Series()?
Example 1: Creating a Series from a list
Example
import
pandas
as
pd
Create a simple Series
data
=
[
10
,
20
,
30
,
40
]
s
=
pd.
Series
(
data
)
(
s
)
Output:
0 10
1 20
2 30
3 40
dtype: int64
Explanation:
- Data
[10, 20, 30, 40]is converted into a Series. - Indexes start at 0 by default.
Example 2: Specifying an index
Example
Create a Series and specify an index
data
=
[
10
,
20
,
30
,
40
]
index
=
[
'a'
,
'b'
,
'c'
,
'd'
]
s
=
pd.
Series
(
data
,
index
=
index
)
(
s
)
Output:
a 10
b 20
c 30
d 40
dtype: int64
Explanation:
- The index is specified as
['a', 'b', 'c', 'd']instead of the default 0, 1, 2, 3.
Example 3: Creating a Series from a dictionary
Example
Create a Series from a dictionary
data
=
{
'a'
:
10
,
'b'
:
20
,
'c'
:
30
,
'd'
:
40
}
s
=
pd.
Series
(
data
)
(
s
)
Output:
a 10
b 20
c 30
d 40
dtype: int64
Explanation:
- The dictionary keys automatically become the Series index and the values become the data.
Example 4: Specifying a data type
Example
Create a Series and specify the data type as float
data
=
[
10
,
20
,
30
,
40
]
s
=
pd.
Series
(
data
,
dtype
=
float
)
(
s
)
Output:
0 10.0
1 20.0
2 30.0
3 40.0
dtype: float64
Explanation:
- The data type is specified as
floatso all values are displayed as floats.
Common Series operations
1. Accessing data
You can access data in a Series by index.
Example
s
=
pd.
Series
(
[
10
,
20
,
30
,
40
]
,
index
=
[
'a'
,
'b'
,
'c'
,
'd'
]
)
(
s
[
'b'
]
)
Output: 20
2. Modifying data
You can modify data in a Series by index.
Example
s
[
'b'
]
=
25
(
s
)
Output:
a 10
b 25
c 30
d 40
dtype: int64
3. Slicing
You can slice a Series.
Example
(
s
[
'b'
:
'd'
]
)
Output:
b 25
c 30
d 40
dtype: int64
4. Mathematical operations
You can perform mathematical operations on a Series.
Example
(
s *
2
)
Output:
a 20
b 50
c 60
d 80
dtype: int64
Pandas Series API manual