Saturday, November 16, 2024
Google search engine
HomeLanguagespandas.array() function in Python

pandas.array() function in Python

This method is used to create an array from a sequence in desired data type.

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“.

Below is the implementation of the above method with some examples :

Example 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)


Output :

<PandasArray>
['1', '2', '3', '4', '5']
Length: 5, dtype: str32

Example 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)


Output :

<PandasArray>
[1, 2, 3, 4, 5]
Length: 5, dtype: int8
RELATED ARTICLES

Most Popular

Recent Comments