Pandas ``Series.from_array()`` 使用方法


发布日期 : 2023-12-20 12:55:50 UTC

访问量: 10 次浏览

Python Pandas Series.from\_array()

Pandas 系列是一个带有轴标签的一维 ndarray。标签不需要是唯一的,但必须是一个可散列的类型。
该对象支持基于整数和标签的索引,并提供了大量的方法来执行涉及索引的操作。

Pandas Series.from_array() 函数从一个数组中构造一个系列对象。我们还可以在创建时设置系列的名称和索引。

语法:
Series.from_array(arr, index=None, name=None, dtype=None, copy=False, fastpath=False)

参数:

arr:数组,用于构建系列。

index:设置系列的索引。

name:设置系列的名称

返回:系列

例子#1:使用Series.from_array() 函数从一个数组中构造一个系列对象。

# importing pandas as pd
import pandas as pd
  
# Creating an array
array = ['New York', 'Chicago', 'Toronto', 'Lisbon', 'Rio']
  
# Create the Index
index_ = ['City 1', 'City 2', 'City 3', 'City 4', 'City 5'] 
  
# Creating the series
sr = pd.Series.from_array(arr = array, index = index_)
  
# Print the series
print(sr)

输出 :

Python Pandas Series.from_array()

正如我们在输出中看到的,Series.from_array() 函数已经成功地从一个数组中构建了一个系列对象。

示例#2:使用Series.from_array() 函数从数组中构造一个系列对象。同时设置系列的名称

# importing pandas as pd
import pandas as pd
  
# Creating an array
array = [11, 21, 8, 18, 65, 84, 32, 10, 5, 24, 32]
  
# Create the Index
index_ = pd.date_range('2010-10-09', periods = 11, freq ='M')
  
# Creating the series
# set the index
# set the name
sr = pd.Series.from_array(arr = array, index = index_, name = 'My_series')
  
# Print the series
print(sr)

输出 :

Python Pandas Series.from_array()

正如我们在输出中看到的,Series.from_array() 函数已经成功地从一个数组中构建了一个系列对象。
我们还设置了系列的名称。