将 NumPy 数组转换为 Pandas 系列

numpypandasserver side programmingprogramming

Numpy 数组是 N 维数组,也称为 ndarray,它是 NumPy 库的主要对象。同样,pandas 系列是 pandas 库的一维数据结构。pandas 和 NumPy 都是 python 中有效使用的开源库。下面我们可以看到一维 numpy 数组。

NumPy 数组
array([1, 2, 3, 4])

pandas 系列是带有标记索引的一维数据结构,它与一维 NumPy 数组非常相似。

Pandas Series:
0    1
1    2
2    3
3    4
4    5
dtype: int64

从上面的代码块中我们可以看到 pandas 系列对象,它有 5 个整数元素,每个元素都标有位置索引值。在下面的文章中,我们将 NumPy 数组转换为 Pandas 系列对象。

输入输出场景

让我们看看输入输出场景,以了解如何将 NumPy 数组转换为 Pandas 系列。

假设我们有一个包含几个值的一维 Numpy 数组,在输出中,我们将看到从 numpy 数组转换而来的 pandas 系列对象。

输入 numpy 数组:
[1 2 3 4]

输出系列:
0    1
1    2
2    3
3    4
dtype: int64

要将 Numpy 数组转换为 Pandas Series,我们可以使用 pandas.Series() 方法。

pandas.Series() 方法

pandas.Series () 方法用于根据给定的数据创建 Series 对象。该方法返回一个 Series 对象。以下是此方法的语法 –

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

其中,

  • data:可迭代对象、字典或标量值。

  • index:使用此参数指定行标签。默认值为 0 到 n-1。

  • dtype:这是一个字符串值,用于指定系列的数据类型。(可选)

  • name:这是一个字符串值,用于指定系列对象的名称。 (可选)

  • copy:从输入中复制数据,默认值为 False。

示例

让我们使用 pandas.Series() 方法将 NumPy 数组转换为 pandas 系列。

# 导入模块
import numpy as np
import pandas as pd

# 创建一维 numpy 数组
numpy_array = np.array([1, 2, 8, 3, 0, 2, 9, 4])
print("输入 numpy 数组:")
print(numpy_array)

# 将 NumPy 数组转换为系列
s = pd.Series(numpy_array)
print("输出系列:")
打印(s)

输出

输入 numpy 数组:
[1 2 8 3 0 2 9 4]
输出系列:
0    1
1    2
2    8
3    3
4    0
5    2
6    9
7    4
dtype: int64

首先,使用整数元素创建一个一维 numpy 数组,然后将该数组转换为 pandas Series 对象。

示例

在此示例中,该系列是从浮点数的 NumPy 数组转换而来的。在转换过程中,我们将使用 index 参数为系列对象指定行标签。

# 导入模块
import numpy as np
import pandas as pd

# 创建一维 numpy 数组
numpy_array = np.array([1, 2.8, 3.0, 2, 9, 4.2])
print("输入 numpy 数组:")
print(numpy_array)

# 将 NumPy 数组转换为系列
s = pd.Series(numpy_array, index=list('abcdef'))
print("输出系列:")
print(s)

输出

输入 numpy 数组:
[1. 2.8 3. 2. 9. 4.2]
输出系列:
a    1.0
b    2.8
c    3.0
d    2.0
e    9.0
f    4.2
dtype: float64

将字符串列表提供给 Series 构造函数的 index 参数。

示例

在此示例中,我们将二维 numpy 数组转换为 series 对象。

# 导入模块
import numpy as np
import pandas as pd

# 创建 numpy 数组
numpy_array = np.array([[4, 1], [7, 2], [2, 0]])
print("输入 numpy 数组:")
print(numpy_array)

# 将 NumPy 数组转换为 Series
s = pd.Series(map(lambda x: x, numpy_array))
print("输出 Series:")
print(s)

输出

输入 numpy 数组:
[[4 1]
 [7 2]
 [2 0]]
输出系列:
0    [4, 1]
1    [7, 2]
2    [2, 0]
dtype: object

通过结合使用 map 和 lambda 函数,我们将二维 numpy 数组转换为系列对象。转换后的系列的数据类型为对象类型,每个系列元素都有一个整数数组。

示例

我们再举一个例子,将二维数组转换为系列对象。

# 导入模块
import numpy as np
import pandas as pd

# 创建 numpy 数组
numpy_array = np.array([[4, 1], [7, 2], [2, 0]])
print("输入 numpy 数组:")
print(numpy_array)

# 将 NumPy 数组转换为系列
s = pd.Series(map(lambda x: x[0], numpy_array))
print("输出系列:")
print(s)

输出

输入 numpy 数组:
[[4 1]
 [7 2]
 [2 0]]
输出系列:
0    4
1    7
2    2
dtype: int64

此处使用二维 numpy 数组的第一行元素创建该系列。


相关文章