Python中的 pandas.array()函数
此方法用于从所需数据类型的序列创建数组。
Syntax : pandas.array(data: Sequence[object], dtype: Union[str, numpy.dtype, pandas.core.dtypes.base.ExtensionDtype, NoneType] = None, copy: bool = True)
Parameters :
- data : Sequence of objects. The scalars inside `data` should be instances of the scalar type for `dtype`. It’s expected that `data` represents a 1-dimensional array of data. When `data` is an Index or Series, the underlying array will be extracted from `data`.
- dtype : tr, np.dtype, or ExtensionDtype, optional. The dtype to use for the array. This may be a NumPy dtype or an extension type registered with pandas.
- copy : bool, default True. Whether to copy the data, even if not necessary. Depending on the type of `data`, creating the new array may require copying data, even if “copy=False“.
以下是上述方法的实现以及一些示例:
示例 1:
Python3
# 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)
Python3
# 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)
输出 :
['1', '2', '3', '4', '5']
Length: 5, dtype: str32
示例 2:
Python3
# 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)
输出 :
[1, 2, 3, 4, 5]
Length: 5, dtype: int8