Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas pd.Series() function

Pandas pd.Series() function

Pandas Series API Manual Pandas Series API manual

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:

  1. data: data, which can be a list, dictionary, NumPy array, etc.
  2. index: index, used to label the data. If omitted, it defaults to starting at 0.
  3. dtype: data type, such as int、float、str , etc.
  4. name: the name of the Series, usually used to label the data.
  5. 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

)

print

(

s

)

Output:

0    10

1    20

2    30

3    40

dtype: int64

Explanation:


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

)

print

(

s

)

Output:

a    10

b    20

c    30

d    40

dtype: int64

Explanation:


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

)

print

(

s

)

Output:

a    10

b    20

c    30

d    40

dtype: int64

Explanation:


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

)

print

(

s

)

Output:

0    10.0

1    20.0

2    30.0

3    40.0

dtype: float64

Explanation:


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'

]

)

print

(

s

[

'b'

]

)

 

Output: 20

2. Modifying data

You can modify data in a Series by index.

Example

s

[

'b'

]

=

25

print

(

s

)

Output:

a    10

b    25

c    30

d    40

dtype: int64

3. Slicing

You can slice a Series.

Example

print

(

s

[

'b'

:

'd'

]

)

Output:

b    25

c    30

d    40

dtype: int64

4. Mathematical operations

You can perform mathematical operations on a Series.

Example

print

(

s *

2

)

Output:

a    20

b    50

c    60

d    80

dtype: int64

Pandas Series API Manual Pandas Series API manual