Python中的pandas.array()函数
该方法用于从一个所需数据类型的序列中创建一个数组。
语法 :
pandas.array(data: Sequence[object], dtype: Union[str, numpy.dtype, pandas.core.dtypes.base.ExtensionDtype, NoneType] = None, copy: bool = True)
参数 :
- data:对象的序列。
data
内的标量应该是dtype
的标量类型的实例。我们希望data
代表一个一维的数据数组。当data
是一个索引或系列时,底层数组将从data
中提取。 - dtype : tr, np.dtype, or ExtensionDtype, optional.数组要使用的dtype。可以是NumPy的dtype,也可以是在pandas注册的扩展类型。
- copy : bool, default True.是否复制数据,即使没有必要。根据
data
的类型,创建新的数组可能需要复制数据,即使 “copy=False”。
下面是上述方法的实现和一些例子。
例子1 :
# importing packages
import pandas
# create Pandas array with dtype string
pd_arr = pandas.array(data=[1,2,3,4,5],dtype=str)
# print the formed array
print(pd_arr)
输出 :
<PandasArray>
['1', '2', '3', '4', '5']
Length: 5, dtype: str32
例子2 :
# importing packages
import pandas
import numpy
# create Pandas array with dtype from numpy
pd_arr = pandas.array(data=['1', '2', '3', '4', '5'],
dtype=numpy.int8)
# print the formed array
print(pd_arr)
输出 :
<PandasArray>
[1, 2, 3, 4, 5]
Length: 5, dtype: int8