Python pandas dataframe dtype

Pandas.DataFrame.dtypes: возвращает тип данных столбца

Pandas DataFrame dtypes — это встроенное свойство, которое возвращает типы данных столбца DataFrame. Когда вы проводите анализ данных, важно убедиться, что вы используете правильные типы данных; в противном случае можно получить неожиданные результаты или ошибки.

В какой-то момент процесса анализа данных вам потребуется явно преобразовать данные из одного типа в другой. В этом посте будут обсуждаться основные типы данных Pandas (иначе dtypes), как они сопоставляются с типами данных python и numpy.

Синтаксис

Возвращаемое значение

Атрибут Pandas DataFrame.dtypes возвращает dtypes в DataFrame.

Свойство dtypes возвращает серию с типом данных каждого столбца.

Пример dtypes в Pandas

Тип данных — это, по сути, внутренняя конструкция языка программирования, которая используется для понимания того, как хранить данные и управлять ими. Например, программа должна знать, что вы можете сложить два числа, например 5 + 5, чтобы получить 10. Или, если у вас есть две строки, такие как «приложение» и «дивиденд», вы можете объединить (сложить) их вместе, чтобы получить «аппдивиденд».

Как мы видим в выводе, атрибут DataFrame.dtypes успешно возвратил типы данных каждого столбца в данном DataFrame.

Проверка типа данных NaN

Давайте проверим тип данных NaN в Pandas. См. следующий код.

Значения Pandas NaN возвращают тип данных Float.

Давайте добавим еще один столбец с именем profitDate и посмотрим на результат.

‘arrivalDate’ : [ pd . Timestamp ( ‘20180310’ ) , pd . Timestamp ( ‘20190310’ ) , pd . Timestamp ( ‘20140310’ ) ] >

В нашем примере dtype прибытияDate — это datetime64 в наносекундах.

Читайте также:  50 projects in 50 days html css javascript

Сопоставление dtype Pandas

Из приведенной выше таблицы видно, что тип данных String определяется как Object в Pandas и еще три типа в библиотеке Numpy. Таким образом, определение одного типа данных отличается в разных библиотеках.

По большей части вам не нужно беспокоиться о проверке, следует ли пытаться явно принудить тип Pandas к соответствующему типу Numpy.

В большинстве случаев будет работать использование типов Pandas по умолчанию int64 и float64. Единственная причина, по которой я включил приведенную выше таблицу, заключается в том, что иногда вы могли видеть, что типы Numpy всплывают в Интернете или в вашем анализе.

Pandas DataFrame info()

Функция df.info() выводит краткую сводку DataFrame и информацию о DataFrame, включая тип dtype индекса и dtype столбца, ненулевые значения и использование памяти.

Источник

pandas arrays, scalars, and data types#

For most data types, pandas uses NumPy arrays as the concrete objects contained with a Index , Series , or DataFrame .

For some data types, pandas extends NumPy’s type system. String aliases for these types can be found at dtypes .

pandas and third-party libraries can extend NumPy’s type system (see Extension types ). The top-level array() method can be used to create a new array, which may be stored in a Series , Index , or as a column in a DataFrame .

PyArrow#

This feature is experimental, and the API can change in a future release without warning.

The arrays.ArrowExtensionArray is backed by a pyarrow.ChunkedArray with a pyarrow.DataType instead of a NumPy array and data type. The .dtype of a arrays.ArrowExtensionArray is an ArrowDtype .

Pyarrow provides similar array and data type support as NumPy including first-class nullability support for all data types, immutability and more.

Читайте также:  Https lk uksn ru index php личный кабинет

The table below shows the equivalent pyarrow-backed ( pa ), pandas extension, and numpy ( np ) types that are recognized by pandas. Pyarrow-backed types below need to be passed into ArrowDtype to be recognized by pandas e.g. pd.ArrowDtype(pa.bool_())

Pyarrow-backed string support is provided by both pd.StringDtype(«pyarrow») and pd.ArrowDtype(pa.string()) . pd.StringDtype(«pyarrow») is described below in the string section and will be returned if the string alias «string[pyarrow]» is specified. pd.ArrowDtype(pa.string()) generally has better interoperability with ArrowDtype of different types.

While individual values in an arrays.ArrowExtensionArray are stored as a PyArrow objects, scalars are returned as Python scalars corresponding to the data type, e.g. a PyArrow int64 will be returned as Python int, or NA for missing values.

Pandas ExtensionArray backed by a PyArrow ChunkedArray.

An ExtensionDtype for PyArrow data types.

For more information, please see the PyArrow user guide

Datetimes#

NumPy cannot natively represent timezone-aware datetimes. pandas supports this with the arrays.DatetimeArray extension array, which can hold timezone-naive or timezone-aware values.

Timestamp , a subclass of datetime.datetime , is pandas’ scalar type for timezone-naive or timezone-aware datetime data. NaT is the missing value for datetime data.

Pandas replacement for python datetime.datetime object.

(N)ot-(A)-(T)ime, the time equivalent of NaN.

Properties#

Return numpy datetime64 format in nanoseconds.

Return the day of the year.

Return the day of the year.

Return the number of days in the month.

Return the number of days in the month.

Return True if year is a leap year.

Check if the date is the last day of the month.

Check if the date is the first day of the month.

Читайте также:  Python datetime strptime format

Check if date is last day of the quarter.

Check if the date is the first day of the quarter.

Return True if date is last day of the year.

Return True if date is first day of the year.

Источник

Оцените статью