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

Pandas Data Structures - Series

Pandas Data Structures - Series

Series is a core data structure in Pandas, similar to a one-dimensional array, with data and an index.

Series can store any data type (integers, floats, strings, etc.) and access elements via labels (the index).

The Series data structure is very useful because it can handle various data types while maintaining efficient data manipulation capabilities, such as quickly accessing and manipulating data via labels.

Series features:

We can use the Pandas library to create a Series object and specify its index, name, and values:

Example

import

pandas

as

pd

Create a Series object with name 'A' and values 1, 2, 3, 4

Default index is 0, 1, 2, 3

series

=

pd.

Series

(

[

1

,

2

,

3

,

4

]

,

name

=

'A'

)

Display the Series object

print

(

series

)

If you want to explicitly set the index, you can do this:

custom_index

=

[

1

,

2

,

3

,

4

]

 

Custom index

series_with_index

=

pd.

Series

(

[

1

,

2

,

3

,

4

]

,

index

=

custom_index

,

name

=

'A'

)

Display the Series object with a custom index

print

(

series_with_index

)

The output is:

0    1

1    2

2    3

3    4

Name: A, dtype: int64

1    1

2    2

3    3

4    4

Name: A, dtype: int64

Series is a fundamental data structure in Pandas, similar to a one-dimensional array or list, but with labels (an index), making data more flexible to process and analyze.

The following is a detailed introduction to Series in Pandas.


Create a Series

You can use the pd.Series() constructor to create a Series object, passing a data array (which can be a list, NumPy array, etc.) and an optional index array.

pandas.Series(data=None, index=None, dtype=None, name=None, copy=False, fastpath=False)

Parameter Description:

Create a simple Series instance:

Example

import

pandas

as

pd

a

=

[

1

,

2

,

3

]

myvar

=

pd.

Series

(

a

)

print

(

myvar

)

The output is as follows:

As shown above, if no index is specified, index values start from 0, and we can read data by index value:

Example

import

pandas

as

pd

a

=

[

1

,

2

,

3

]

myvar

=

pd.

Series

(

a

)

print

(

myvar

[

1

]

)

The output is as follows:

2

We can specify index values, as in the following example:

Example

import

pandas

as

pd

a

=

[

"Google"

,

"Runoob"

,

"Wiki"

]

myvar

=

pd.

Series

(

a

,

index

=

[

"x"

,

"y"

,

"z"

]

)

print

(

myvar

)

The output is as follows:

Read data by index value:

Example

import

pandas

as

pd

a

=

[

"Google"

,

"Runoob"

,

"Wiki"

]

myvar

=

pd.

Series

(

a

,

index

=

[

"x"

,

"y"

,

"z"

]

)

print

(

myvar

[

"y"

]

)

The output is as follows:

Runoob

We can also use a key/value object, similar to a dictionary, to create a Series:

Example

import

pandas

as

pd

sites

=

{

1

:

"Google"

,

2

:

"Runoob"

,

3

:

"Wiki"

}

myvar

=

pd.

Series

(

sites

)

print

(

myvar

)

The output is as follows:

As shown above, the dictionary keys become the index values.

If we only need part of the data in the dictionary, we just specify the indices of the data we need, as in the following example:

Example

import

pandas

as

pd

sites

=

{

1

:

"Google"

,

2

:

"Runoob"

,

3

:

"Wiki"

}

myvar

=

pd.

Series

(

sites

,

index

=

[

1

,

2

]

)

print

(

myvar

)

The output is as follows:

Set the Series name parameter:

Example

import

pandas

as

pd

sites

=

{

1

:

"Google"

,

2

:

"Runoob"

,

3

:

"Wiki"

}

myvar

=

pd.

Series

(

sites

,

index

=

[

1

,

2

]

,

name

=

"RUNOOB-Series-TEST"

)

print

(

myvar

)


Series methods

The following are some commonly used methods of Series:

Method Name Description
index Get the Series index
values Get the Series data part (returns a NumPy array)
head(n) Return the first n rows of the Series (default is 5)
tail(n) Return the last n rows of the Series (default is 5)
dtype Return the data type of the Series
shape Return the shape of the Series (number of rows)
describe() Return the statistical description of the Series (such as mean, standard deviation, minimum, etc.)
isnull() Return a boolean Series indicating whether each element is NaN
notnull() Return a boolean Series indicating whether each element is not NaN
unique() Return the unique values in the Series (deduplicated)
value_counts() Return the count of occurrences of each unique value in the Series
map(func) Apply a specified function to each element in the Series
apply(func) Apply a specified function to each element in the Series, commonly used for custom operations
astype(dtype) Convert the Series to a specified type
sort_values() Sort the elements in the Series (sort by value)
sort_index() Sort the index of the Series
dropna() Remove missing values (NaN) from the Series
fillna(value) Fill missing values (NaN) in the Series
replace(to_replace, value) Replace specified values in the Series
cumsum() Return the cumulative sum of the Series
cumprod() Return the cumulative product of the Series
shift(periods) Shift the elements in the Series by a specified number of steps
rank() Return the rank of elements in the Series
corr(other) Compute the correlation between the Series and another Series (Pearson correlation coefficient)
cov(other) Compute the covariance between the Series and another Series
to_list() Convert the Series to a Python list
to_frame() Convert the Series to a DataFrame
iloc[] Select data by positional index
loc[] Select data by label index

Example

import

pandas

as

pd

Create a Series

data

=

[

1

,

2

,

3

,

4

,

5

,

6

]

index

=

[

'a'

,

'b'

,

'c'

,

'd'

,

'e'

,

'f'

]

s

=

pd.

Series

(

data

,

index

=

index

)

View basic information

print

(

"Index:"

,

s.

index

)

print

(

"Data:"

,

s.

values

)

print

(

"Data type:"

,

s.

dtype

)

print

(

"First two rows:"

,

s.

head

(

2

)

)

Use the map function to double each element

s_doubled

=

s.

map

(

lambda

x: x *

2

)

print

(

"After doubling elements:"

,

s_doubled

)

Compute the cumulative sum

cumsum_s

=

s.

cumsum

(

)

print

(

"Cumulative sum:"

,

cumsum_s

)

Find missing values (there are none here, so all returned values are False)

print

(

"Missing value check:"

,

s.

isnull

(

)

)

Sorting

sorted_s

=

s.

sort_values

(

)

print

(

"Sorted Series:"

,

sorted_s

)

The output is:

索引: Index(['a', 'b', 'c', 'd', 'e', 'f'], dtype='object')

数据: [1 2 3 4 5 6]

数据类型: int64

前两行数据: a    1

b    2

dtype: int64

元素加倍后: a     2

b     4

c     6

d     8

e    10

f    12

dtype: int64

累计求和: a     1

b     3

c     6

d    10

e    15

f    21

dtype: int64

缺失值判断: a    False

b    False

c    False

d    False

e    False

f    False

dtype: bool

排序后的 Series: a    1

b    2

c    3

d    4

e    5

f    6

dtype: int64


More on Series

Create a Series with a default index using a list, dictionary, or array.



# Create Series from list

s = pd.Series([1, 2, 3, 4])



# Create Series using NumPy array

s = pd.Series(np.array([1, 2, 3, 4]))



# Create Series using a dictionary

s = pd.Series({'a': 1, 'b': 2, 'c': 3, 'd': 4})

Basic operations:



# Specify index to create Series

s = pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])



# 获取值

value = s[2]  # 获取索引为2的值

print(s['a'])  # 返回索引标签 'a' 对应的元素



# Get multiple values

subset = s[1:4]  # 获取索引为1到3的值



# Using custom index

value = s['b']  # 获取索引为'b'的值



# Index and value correspondence

for index, value in s.items():

    print(f"Index: {index}, Value: {value}")





# Use slicing syntax to access a portion of the Series

print(s['a':'c'])  # 返回索引标签 'a' 到 'c' 之间的元素

print(s[:3])  # 返回前三个元素



# Assign a value to a specific index label

s['a'] = 10  # 将索引标签 'a' 对应的元素修改为 10



# Add elements by assigning to a new index label

s['e'] = 5  # 在 Series 中添加一个新的元素,索引标签为 'e'



# Use del to delete elements with a specified index label.

del s['a']  # 删除索引标签 'a' 对应的元素



# Use the drop method to delete one or more index labels, and return a new Series.

s_dropped = s.drop(['b'])  # 返回一个删除了索引标签 'b' 的新 Series

Basic arithmetic:

# 算术运算

result = series * 2  # 所有元素乘以2



# 过滤

filtered_series = series[series > 2]  # 选择大于2的元素



# Mathematical functions

import numpy as np

result = np.sqrt(series)  # 对每个元素取平方根

Compute statistics: use Series methods to calculate descriptive statistics.

print(s.sum())  # 输出 Series 的总和

print(s.mean())  # 输出 Series 的平均值

print(s.max())  # 输出 Series 的最大值

print(s.min())  # 输出 Series 的最小值

print(s.std())  # 输出 Series 的标准差

Attributes and methods:



# Get index

index = s.index



# Get value array

values = s.values



# Get descriptive statistics

stats = s.describe()



# Get the indices of the maximum and minimum values

max_index = s.idxmax()

min_index = s.idxmin()



# Other properties and methods

print(s.dtype)   # 数据类型

print(s.shape)   # 形状

print(s.size)    # 元素个数

print(s.head())  # 前几个元素,默认是前 5 个

print(s.tail())  # 后几个元素,默认是后 5 个

print(s.sum())   # 求和

print(s.mean())  # 平均值

print(s.std())   # 标准差

print(s.min())   # 最小值

print(s.max())   # 最大值

Use boolean expressions: filter the Series by conditions.

print(s > 2)  # 返回一个布尔 Series,其中的元素值大于 2

View data type: use the dtype attribute to view the Series' data type.



print(s.dtype)  # 输出 Series 的数据类型

Convert data type: use the astype method to convert the Series to another data type.



s = s.astype('float64')  # 将 Series 中的所有元素转换为 float64 类型

Notes: