On this page
pandas.array
pandas.array(data, dtype=None, copy=True)[source]-
Create an array.
New in version 0.24.0.
Parameters: -
data : Sequence of objects -
The scalars inside
datashould be instances of the scalar type fordtype. It’s expected thatdatarepresents a 1-dimensional array of data.When
datais an Index or Series, the underlying array will be extracted fromdata. -
dtype : str, 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 using
pandas.api.extensions.register_extension_dtype().If not specified, there are two possibilities:
- When
datais aSeries,Index, orExtensionArray, thedtypewill be taken from the data. - Otherwise, pandas will attempt to infer the
dtypefrom the data.
Note that when
datais a NumPy array,data.dtypeis not used for inferring the array type. This is because NumPy cannot represent all the types of data that can be held in extension arrays.Currently, pandas will infer an extension dtype for sequences of
Scalar Type Array Type pandas.Intervalpandas.arrays.IntervalArraypandas.Periodpandas.arrays.PeriodArraydatetime.datetimepandas.arrays.DatetimeArraydatetime.timedeltapandas.arrays.TimedeltaArrayFor all other cases, NumPy’s usual inference rules will be used.
- When
-
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 ifcopy=False.
Returns: - ExtensionArray
-
The newly created array.
Raises: - ValueError
-
When
datais not 1-dimensional.
See also
numpy.array- Construct a NumPy array.
Series- Construct a pandas Series.
Index- Construct a pandas Index.
arrays.PandasArray- ExtensionArray wrapping a NumPy array.
Series.array- Extract the array stored within a Series.
Notes
Omitting the
dtypeargument means pandas will attempt to infer the best array type from the values in the data. As new array types are added by pandas and 3rd party libraries, the “best” array type may change. We recommend specifyingdtypeto ensure that- the correct array type for the data is returned
- the returned array type doesn’t change as new extension types are added by pandas and third-party libraries
Additionally, if the underlying memory representation of the returned array matters, we recommend specifying the
dtypeas a concrete object rather than a string alias or allowing it to be inferred. For example, a future version of pandas or a 3rd-party library may include a dedicated ExtensionArray for string data. In this event, the following would no longer return aarrays.PandasArraybacked by a NumPy array.>>> pd.array(['a', 'b'], dtype=str) <PandasArray> ['a', 'b'] Length: 2, dtype: str32This would instead return the new ExtensionArray dedicated for string data. If you really need the new array to be backed by a NumPy array, specify that in the dtype.
>>> pd.array(['a', 'b'], dtype=np.dtype("<U1")) <PandasArray> ['a', 'b'] Length: 2, dtype: str32Or use the dedicated constructor for the array you’re expecting, and wrap that in a PandasArray
>>> pd.array(np.array(['a', 'b'], dtype='<U1')) <PandasArray> ['a', 'b'] Length: 2, dtype: str32Finally, Pandas has arrays that mostly overlap with NumPy
When data with a
datetime64[ns]ortimedelta64[ns]dtype is passed, pandas will always return aDatetimeArrayorTimedeltaArrayrather than aPandasArray. This is for symmetry with the case of timezone-aware data, which NumPy does not natively support.>>> pd.array(['2015', '2016'], dtype='datetime64[ns]') <DatetimeArray> ['2015-01-01 00:00:00', '2016-01-01 00:00:00'] Length: 2, dtype: datetime64[ns]>>> pd.array(["1H", "2H"], dtype='timedelta64[ns]') <TimedeltaArray> ['01:00:00', '02:00:00'] Length: 2, dtype: timedelta64[ns]Examples
If a dtype is not specified,
datais passed through tonumpy.array(), and aarrays.PandasArrayis returned.>>> pd.array([1, 2]) <PandasArray> [1, 2] Length: 2, dtype: int64Or the NumPy dtype can be specified
>>> pd.array([1, 2], dtype=np.dtype("int32")) <PandasArray> [1, 2] Length: 2, dtype: int32You can use the string alias for
dtype>>> pd.array(['a', 'b', 'a'], dtype='category') [a, b, a] Categories (2, object): [a, b]Or specify the actual dtype
>>> pd.array(['a', 'b', 'a'], ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True)) [a, b, a] Categories (3, object): [a < b < c]Because omitting the
dtypepasses the data through to NumPy, a mixture of valid integers and NA will return a floating-point NumPy array.>>> pd.array([1, 2, np.nan]) <PandasArray> [1.0, 2.0, nan] Length: 3, dtype: float64To use pandas’ nullable
pandas.arrays.IntegerArray, specify the dtype:>>> pd.array([1, 2, np.nan], dtype='Int64') <IntegerArray> [1, 2, NaN] Length: 3, dtype: Int64Pandas will infer an ExtensionArray for some types of data:
>>> pd.array([pd.Period('2000', freq="D"), pd.Period("2000", freq="D")]) <PeriodArray> ['2000-01-01', '2000-01-01'] Length: 2, dtype: period[D]datamust be 1-dimensional. A ValueError is raised when the input has the wrong dimensionality.>>> pd.array(1) Traceback (most recent call last): ... ValueError: Cannot pass scalar '1' to 'pandas.array'. -
© 2008–2012, AQR Capital Management, LLC, Lambda Foundry, Inc. and PyData Development Team
Licensed under the 3-clause BSD License.
https://pandas.pydata.org/pandas-docs/version/0.24.2/reference/api/pandas.array.html