Data type objects ( dtype )#
A data type object (an instance of numpy.dtype class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes the following aspects of the data:
Type of the data (integer, float, Python object, etc.)
Size of the data (how many bytes is in e.g. the integer)
Byte order of the data ( little-endian or big-endian )
If the data type is structured data type , an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float),
what are the names of the “ fields ” of the structure, by which they can be accessed ,
what is the data-type of each field , and
which part of the memory block each field takes.
If the data type is a sub-array, what is its shape and data type.
To describe the type of scalar data, there are several built-in scalar types in NumPy for various precision of integers, floating-point numbers, etc. An item extracted from an array, e.g., by indexing, will be a Python object whose type is the scalar type associated with the data type of the array.
Note that the scalar types are not dtype objects, even though they can be used in place of one whenever a data type specification is needed in NumPy.
Structured data types are formed by creating a data type whose field contain other data types. Each field has a name by which it can be accessed . The parent data type should be of sufficient size to contain all its fields; the parent is nearly always based on the void type which allows an arbitrary item size. Structured data types may also contain nested structured sub-array data types in their fields.
Finally, a data type can describe items that are themselves arrays of items of another data type. These sub-arrays must, however, be of a fixed size.
If an array is created using a data-type describing a sub-array, the dimensions of the sub-array are appended to the shape of the array when the array is created. Sub-arrays in a field of a structured type behave differently, see Field access .
Sub-arrays always have a C-contiguous memory layout.
A simple data type containing a 32-bit big-endian integer: (see Specifying and constructing data types for details on construction)
The corresponding array scalar type is int32 .
A structured data type containing a 16-character string (in field ‘name’) and a sub-array of two 64-bit floating-point number (in field ‘grades’):
Items of an array of this data type are wrapped in an array scalar type that also has two fields:
Specifying and constructing data types#
Whenever a data-type is required in a NumPy function or method, either a dtype object or something that can be converted to one can be supplied. Such conversions are done by the dtype constructor:
dtype (dtype[, align, copy])
Create a data type object.
What can be converted to a data-type object is described below:
The default data type: float_ .
The 24 built-in array scalar type objects all convert to an associated data-type object. This is true for their sub-classes as well.
Note that not all data-type information can be supplied with a type-object: for example, flexible data-types have a default itemsize of 0, and require an explicitly given size to be useful.
The generic hierarchical type objects convert to corresponding type objects according to the associations:
Deprecated since version 1.19: This conversion of generic scalar types is deprecated. This is because it can be unexpected in a context such as arr.astype(dtype=np.floating) , which casts an array of float32 to an array of float64 , even though float32 is a subdtype of np.floating .
Several python types are equivalent to a corresponding array scalar when used to generate a dtype object:
Note that str refers to either null terminated bytes or unicode strings depending on the Python version. In code targeting both Python 2 and 3 np.unicode_ should be used as a dtype for strings. See Note on string types .
All other types map to object_ for convenience. Code should expect that such types may map to a specific (new) dtype in the future.
Any type object with a dtype attribute: The attribute will be accessed and used directly. The attribute must return something that is convertible into a dtype object.
Several kinds of strings can be converted. Recognized strings can be prepended with ‘>’ ( big-endian ), ‘<‘ ( little-endian ), or ‘=’ (hardware-native, the default), to specify the byte order.
Each built-in data-type has a character code (the updated Numeric typecodes), that uniquely identifies it.
The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are
What does dtype=object mean while creating a numpy array?
I was experimenting with numpy arrays and created a numpy array of strings:
As I have read from from their official guide, operations on numpy array are propagated to individual elements. So I did this:
But then I get this error:
But when I used dtype=object
while creating the array I am able to do all operations.
Can anyone tell me why this is happening?
1 Answer 1
NumPy arrays are stored as contiguous blocks of memory. They usually have a single datatype (e.g. integers, floats or fixed-length strings) and then the bits in memory are interpreted as values with that datatype.
Creating an array with dtype=object is different. The memory taken by the array now is filled with pointers to Python objects which are being stored elsewhere in memory (much like a Python list is really just a list of pointers to objects, not the objects themselves).
Arithmetic operators such as * don’t work with arrays such as ar1 which have a string_ datatype (there are special functions instead — see below). NumPy is just treating the bits in memory as characters and the * operator doesn’t make sense here. However, the line
works because now the array is an array of (pointers to) Python strings. The * operator is well defined for these Python string objects. New Python strings are created in memory and a new object array with references to the new strings is returned.
Name already in use
numpy / doc / source / reference / arrays.dtypes.rst
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
A data type object (an instance of :class:`numpy.dtype` class) describes how the bytes in the fixed-size block of memory corresponding to an array item should be interpreted. It describes the following aspects of the data:
- Type of the data (integer, float, Python object, etc.)
- Size of the data (how many bytes is in e.g. the integer)
- Byte order of the data ( :term:`little-endian` or :term:`big-endian` )
- If the data type is :term:`structured data type` , an aggregate of other data types, (e.g., describing an array item consisting of an integer and a float),
- what are the names of the » :term:`fields <field>` » of the structure, by which they can be :ref:`accessed <arrays.indexing.fields>` ,
- what is the data-type of each :term:`field` , and
- which part of the memory block each field takes.
To describe the type of scalar data, there are several :ref:`built-in scalar types <arrays.scalars.built-in>` in NumPy for various precision of integers, floating-point numbers, etc. An item extracted from an array, e.g., by indexing, will be a Python object whose type is the scalar type associated with the data type of the array.
Note that the scalar types are not :class:`dtype` objects, even though they can be used in place of one whenever a data type specification is needed in NumPy.
Structured data types are formed by creating a data type whose :term:`field` contain other data types. Each field has a name by which it can be :ref:`accessed <arrays.indexing.fields>` . The parent data type should be of sufficient size to contain all its fields; the parent is nearly always based on the :class:`void` type which allows an arbitrary item size. Structured data types may also contain nested structured sub-array data types in their fields.
Finally, a data type can describe items that are themselves arrays of items of another data type. These sub-arrays must, however, be of a fixed size.
If an array is created using a data-type describing a sub-array, the dimensions of the sub-array are appended to the shape of the array when the array is created. Sub-arrays in a field of a structured type behave differently, see :ref:`arrays.indexing.fields` .
Sub-arrays always have a C-contiguous memory layout.
A simple data type containing a 32-bit big-endian integer: (see :ref:`arrays.dtypes.constructing` for details on construction)
The corresponding array scalar type is :class:`int32` .
A structured data type containing a 16-character string (in field ‘name’) and a sub-array of two 64-bit floating-point number (in field ‘grades’):
Items of an array of this data type are wrapped in an :ref:`array scalar <arrays.scalars>` type that also has two fields:
Specifying and constructing data types
Whenever a data-type is required in a NumPy function or method, either a :class:`dtype` object or something that can be converted to one can be supplied. Such conversions are done by the :class:`dtype` constructor:
What can be converted to a data-type object is described below:
The default data type: :class:`float_` .
The 24 built-in :ref:`array scalar type objects <arrays.scalars.built-in>` all convert to an associated data-type object. This is true for their sub-classes as well.
Note that not all data-type information can be supplied with a type-object: for example, flexible data-types have a default itemsize of 0, and require an explicitly given size to be useful.
The generic hierarchical type objects convert to corresponding type objects according to the associations:
:class:`number` , :class:`inexact` , :class:`floating` :class:`float` :class:`complexfloating` :class:`cfloat` :class:`integer` , :class:`signedinteger` :class:`int\_` :class:`unsignedinteger` :class:`uint` :class:`character` :class:`string` :class:`generic` , :class:`flexible` :class:`void` Built-in Python types
Several python types are equivalent to a corresponding array scalar when used to generate a :class:`dtype` object:
:class:`int` :class:`int\_` :class:`bool` :class:`bool\_` :class:`float` :class:`float\_` :class:`complex` :class:`cfloat` :class:`bytes` :class:`bytes\_` :class:`str` :class:`str\_` :class:`buffer` :class:`void` (all others) :class:`object_` Note that str corresponds to UCS4 encoded unicode strings, while string is an alias to bytes_ . The name np.unicode_ is also available as an alias to np.str_ , see :ref:`Note on string types<string-dtype-note>` .
All other types map to object_ for convenience. Code should expect that such types may map to a specific (new) dtype in the future.
Several kinds of strings can be converted. Recognized strings can be prepended with ‘>’ ( :term:`big-endian` ), ‘<‘ ( :term:`little-endian` ), or ‘=’ (hardware-native, the default), to specify the byte order.
Each built-in data-type has a character code (the updated Numeric typecodes), that uniquely identifies it.
The first character specifies the kind of data and the remaining characters specify the number of bytes per item, except for Unicode, where it is interpreted as the number of characters. The item size must correspond to an existing type, or an error will be raised. The supported kinds are
‘?’ boolean ‘b’ (signed) byte ‘B’ unsigned byte ‘i’ (signed) integer ‘u’ unsigned integer ‘f’ floating-point ‘c’ complex-floating point ‘m’ timedelta ‘M’ datetime ‘O’ (Python) objects ‘S’ , ‘a’ zero-terminated bytes (not recommended) ‘U’ Unicode string ‘V’ raw data ( :class:`void` ) Note on string types
For backward compatibility with existing code originally written to support Python 2, S and a typestrings are zero-terminated bytes and numpy.string_ continues to alias numpy.bytes_. For unicode strings, use U , numpy.str_, or numpy.unicode_. For signed bytes that do not need zero-termination b or i1 can be used.
A short-hand notation for specifying the format of a structured data type is a comma-separated string of basic formats.
A basic format in this context is an optional shape specifier followed by an array-protocol type string. Parenthesis are required on the shape if it has more than one dimension. NumPy allows a modification on the format in that any string that can uniquely identify the type can be used to specify the data-type in a field. The generated data-type fields are named ‘f0’ , ‘f1’ , . ‘f<N-1>’ where N (>1) is the number of comma-separated basic formats in the string. If the optional shape specifier is provided, then the data-type for the corresponding field describes a sub-array.
- field named f0 containing a 32-bit integer
- field named f1 containing a 2 x 3 sub-array of 64-bit floating-point numbers
- field named f2 containing a 32-bit floating-point number
- field named f0 containing a 3-character string
- field named f1 containing a sub-array of shape (3,) containing 64-bit unsigned integers
- field named f2 containing a 3 x 4 sub-array containing 10-character strings
The first argument must be an object that is converted to a zero-sized flexible data-type object, the second argument is an integer providing the desired itemsize.
The first argument is any object that can be converted into a fixed-size data-type object. The second argument is the desired shape of this type. If the shape parameter is 1, then the data-type object used to be equivalent to fixed dtype. This behaviour is deprecated since NumPy 1.17 and will raise an error in the future. If shape is a tuple, then the new dtype defines a sub-array of the given shape.
obj should be a list of fields where each field is described by a tuple of length 2 or 3. (Equivalent to the descr item in the :obj:`
The first element, field_name, is the field name (if this is » then a standard field name, ‘f#’ , is assigned). The field name may also be a 2-tuple of strings where the first string is either a «title» (which may be any string or unicode string) or meta-data for the field which can be any object, and the second string is the «name» which must be a valid Python identifier.
The second element, field_dtype, can be anything that can be interpreted as a data-type.
The optional third element field_shape contains the shape if this field represents an array of the data-type in the second element. Note that a 3-tuple with a third argument equal to 1 is equivalent to a 2-tuple.
This style does not accept align in the :class:`dtype` constructor as it is assumed that all of the memory is accounted for by the array interface description.
Data-type with fields big (big-endian 32-bit integer) and little (little-endian 32-bit integer):
Data-type with fields R , G , B , A , each being an unsigned 8-bit integer:
This style has two required and three optional keys. The names and formats keys are required. Their respective values are equal-length lists with the field names and the field formats. The field names must be strings and the field formats can be any object accepted by :class:`dtype` constructor.
When the optional keys offsets and titles are provided, their values must each be lists of the same length as the names and formats lists. The offsets value is a list of byte offsets (limited to ctypes.c_int) for each field, while the titles value is a list of titles for each field ( None can be used if no title is desired for that field). The titles can be any object, but when a :class:`str` object will add another entry to the fields dictionary keyed by the title and referencing the same field tuple which will contain the title as an additional tuple member.
The itemsize key allows the total size of the dtype to be set, and must be an integer large enough so all the fields are within the dtype. If the dtype being constructed is aligned, the itemsize must also be divisible by the struct alignment. Total dtype itemsize is limited to ctypes.c_int.
Data type with fields r , g , b , a , each being an 8-bit unsigned integer:
Data type with fields r and b (with the given titles), both being 8-bit unsigned integers, the first at byte position 0 from the start of the field and the second at position 2:
This usage is discouraged, because it is ambiguous with the other dict-based construction method. If you have a field called ‘names’ and a field called ‘formats’ there will be a conflict.
This style allows passing in the :attr:`fields <dtype.fields>` attribute of a data-type object.
obj should contain string or unicode keys that refer to (data-type, offset) or (data-type, offset, title) tuples.
Data type containing field col1 (10-character string at byte position 0), col2 (32-bit float at byte position 10), and col3 (integers at byte position 14):
In NumPy 1.7 and later, this form allows base_dtype to be interpreted as a structured dtype. Arrays created with this dtype will have underlying dtype base_dtype but will have fields and flags taken from new_dtype. This is useful for creating custom structured dtypes, as done in :ref:`record arrays <arrays.classes.rec>` .
This form also makes it possible to specify struct dtypes with overlapping fields, functioning like the ‘union’ type in C. This usage is discouraged, however, and the union mechanism is preferred.
Both arguments must be convertible to data-type objects with the same total size.
32-bit integer, whose first two bytes are interpreted as an integer via field real , and the following two bytes via field imag .
32-bit integer, which is interpreted as consisting of a sub-array of shape (4,) containing 8-bit integers:
32-bit integer, containing fields r , g , b , a that interpret the 4 bytes in the integer as four unsigned integers:
NumPy data type descriptions are instances of the :class:`dtype` class.
The type of the data is described by the following :class:`dtype` attributes:
Трюки Pandas от RealPython
К старту флагманского курса по Data Science делимся сокращённым переводом из блога RealPython о трюках с Pandas, материал начинается с конфигурирования запуска библиотеки и заканчиваются примерами работы с операторами и их приоритетом. Затрагивается тема экономии памяти, сжатие фреймов, интроспекция GroupBy через итерацию и другие темы. Подробности, как всегда, под катом.
1. Параметры запуска интерпретатора
Возможно, вы сталкивались с богатыми опциями и настройками системы Pandas. Установка настраиваемых параметров Pandas при запуске интерпретатора значительно снижает производительность, особенно при работе в среде сценариев. Можно воспользоваться pd.set_option() для настройки по своему усмотрению с помощью Python или в файле запуска IPython. Параметры используют точечную нотацию: pd.set_option (‘display.max_colwidth’, 25) , которая хорошо подходит для вложенного словаря параметров:
Запустив сеанс интерпретатора, вы увидите, что сценарий запуска выполнен и Pandas автоматически импортируется с вашим набором опций:
Воспользуемся данными abalone в репозитории машинного обучения UCI, чтобы продемонстрировать заданное в файле запуска форматирование. Сократим данные до 14 строк с точностью до 4 цифр для чисел с плавающей точкой:
Позже вы увидите этот набор данных и в других примерах.
2. Игрушечные cтруктуры данных с помощью модуля тестирования Pandas
Модуль pandas.util.testing был удалён в Pandas 1.0. Публичный API для тестирования из pandas.testing теперь ограничен assert_extension_array_equal() , assert_frame_equal() , assert_series_equal() и assert_index_equal() . Автор признаёт, что узнал вкус своего лекарства за то, что полагался на недокументированные части библиотеки Pandas.
В модуле Pandas testing скрыт ряд удобных функций для быстрого построения квазиреалистичных Series и фреймов данных:
Их около 30, полный список можно увидеть, вызвав dir() на объекте модуля. Вот несколько вариантов:
Они полезны для бенчмаркинга, тестирования утверждений и экспериментов с не очень хорошо знакомыми методами Pandas.
3. Используйте преимущества методов доступа
Возможно, вы слышали о термине акcессор, который чем-то напоминает геттер (хотя геттеры и сеттеры используются в Python нечасто). В нашей статье будем называть аксессором свойство, которое служит интерфейсом для дополнительных методов. В Series [на момент написания оригинальной статьи] их три, сегодня их 4:
Да, приведённое выше определение многозначно, поэтому до обсуждения внутреннего устройства посмотрим на примеры.
.cat — для категориальных данных;
.str — для строковых (объектных) данных;
.dt — для данных, подобных времени.
Начнём с .str : представьте, что у вас есть необработанные данные о городе/области/индексе в виде одного поля в Series Pandas. Строковые методы Pandas векторизованы, то есть работают со всем массивом без явного цикла for:
Для примера сложнее предположим, что вы хотите разделить три компонента city/state/ZIP аккуратно на поля фрейма данных. Вы можете передать регулярное выражение в .str.extract() , чтобы «извлечь» части каждой ячейки в Series. В .str.extract() , .str — это аксессор, а .str.extract() — метод аксессора:
Код иллюстрирует цепочку методов, где .str.extract (regex) вызывается на результате addr.str.replace (‘.’, ») , который очищает использование точек, чтобы получить красивую двухсимвольную аббревиатуру штата. Полезно немного знать о том, как работают эти методы-аксессоры, чтобы понимать, почему нужно использовать их, а не что-то вроде addr.apply (re.findall, …) . Каждый аксессор — это класс Python:
.str отображается на StringMethods .
.dt отображается на CombinedDatetimelikeProperties .
.cat — на CategoricalAccessor .
Эти отдельные классы затем «прикрепляются» к Series с помощью CachedAccessor . Именно когда классы обёрнуты в CachedAccessor , происходит магия.
CachedAccessor вдохновлён конструкцией «кэшированного свойства»: свойство вычисляется только один раз для каждого экземпляра, а затем заменяется обычным атрибутом. Это происходит путём перегрузки метода .__get__() , который является частью протокола дескриптора Python.
Если вы хотите прочитать больше о работе дескрипторов, смотрите Descriptor HOWTO и этот пост о дизайне кэшированных свойств. В Python 3 также появился functools.lru_cache() , предлагающий аналогичную функциональность. Паттерн можно найти повсюду, например в пакете aiohttp .
Второй аксессор, .dt , предназначен для данных о времени. Технически он принадлежит к DatetimeIndex Pandas, и если его вызывать для Series, то сначала он преобразуется в DatetimeIndex :
Третий аксессор, .cat , — только для категориальных данных, которые вы вскоре увидите в отдельном разделе.
4. Создание индекса времени даты из столбцов компонентов
Если говорить о данных, подобных времени, как в daterng , можно создать Pandas DatetimeIndex из нескольких компонентных столбцов, вместе эти столбцы образуют дату или время:
Наконец, вы можете отказаться от старых отдельных столбцов и преобразовать их в Series:
Интуитивно суть передачи фрейма данных в том, что DataFrame похож на словарь Python, где имена столбцов — это ключи, а отдельные столбцы (Series) — значения словаря. Поэтому pd.to_datetime (df[datecols].to_dict (orient=’list’)) здесь также будет работать.
Это — зеркало конструкции datetime.datetime в Python, где вы передаёте аргументы с ключевыми словами, например datetime.datetime(year=2000, month=1, day=15, hour=10) .
5. Использование категориальных данных для экономии времени и места
Одна из мощных возможностей Pandas — её объект типа данных (dtype) Categorical . Даже если вы не всегда работаете с гигабайтами данных в оперативной памяти, вы наверняка сталкивались со случаями, когда простые операции над большим DataFrame зависают более чем на несколько секунд.
dtype Pandas object — часто отличный кандидат для преобразования в категориальные данные. ( object — это контейнер для str , разнородных типов данных или «других» типов.) Строки занимают значительное место в памяти:
Я вызвал sys.getsizeof() , чтобы показать память, занимаемую каждым отдельным значением в Series. Помните, что это объекты Python, у них есть издержки ресурсов. ( sys.getsizeof (») вернёт 49 байт). Есть метод colors.memory_usage() , который суммирует использование памяти и полагается на атрибут .nbytes базового массива NumPy. Не увязните в этих деталях: важно относительное использование памяти, возникающее в результате преобразования типов, об этом ниже.
А что если бы мы могли взять перечисленные выше уникальные цвета и отобразить каждый из них в занимающее меньше места целое число? Наивная реализация:
Другой способ сделать то же самое в Pandas — pd.factorize (colors) :
Так или иначе объект кодируется как перечислимый тип (категориальная переменная).
Вы сразу заметите, что использование памяти сократилось почти вдвое по сравнению с использованием полных строк с dtype object . Ранее в разделе об аксессорах я упоминал категориальный асцессор .cat . Приведённый выше пример с mapper — грубая иллюстрация того, что происходит внутри dtype Categorical в Pandas:
«Использование памяти Categorical пропорционально количеству категорий плюс длина данных. Напротив, object dtype — это константа, умноженная на длину данных» (Источник).
В colors выше есть соотношение двух значений на каждое уникальное значение, то есть на категорию:
Экономия памяти от преобразования в Categorical хороша, но невелика:
Но, если у вас будет, например, много демографических данных, где мало уникальных значений, объём требуемой памяти уменьшится в 10 раз:
Кроме того, повышается эффективность вычислений: для категориальных Series строковые операции [выполняются над атрибутом .cat.categories , а не над каждым исходным элементом Series . Другими словами, операция выполняется один раз для каждой уникальной категории, а результаты отображаются обратно на значения. Категориальные данные имеют аксессор .cat — окно в атрибуты и методы манипулирования категориями:
Можно воспроизвести что-то похожее на пример выше, который делался вручную:
Всё, что вам нужно сделать, чтобы в точности повторить предыдущий ручной вывод, — это изменить порядок кодов:
Обратите внимание, что dtype — это int8 NumPy, 8-битное знаковое целое, которое может принимать значения от −127 до 128. Для представления значения в памяти требуется только один байт. 64-битные знаковые int были бы излишеством с точки зрения потребления памяти. Грубый пример привёл к данным int64 по умолчанию, тогда как Pandas достаточно умна, чтобы привести категориальные данные к минимально возможному числовому dtype.
Большинство атрибутов .cat связаны с просмотром и манипулированием самими базовыми категориями:
6. Интроспекция объектов Groupby через итерацию
При вызове df.groupby (‘x’) результирующие объекты Pandas groupby могут быть немного непрозрачными. Этот объект инстанцируется лениво и сам по себе не имеет никакого осмысленного представления. Продемонстрируем это на наборе данных abalone из первого примера:
Хорошо, теперь у вас есть объект groupby , но что это за штука и как её увидеть? Прежде чем вызвать что-то вроде grouped.apply (func) , вы можете воспользоваться тем, что объекты groupby можно итерировать:
Нечто, получаемое grouped.__iter__() , представляет собой кортеж (name, subsetted object) , где name — это значение столбца группировки, а subsetted object — это DataFrame — подмножество исходного DataFrame на основе любого указанного вами условия группировки, то есть данные разбиваются по группам:
Соответственно объект groupby также имеет .groups и групповой геттер — .get_group() :
Независимо от того, какие вычисления вы выполняете над grouped , будь то отдельный метод Pandas или пользовательская функция, каждый из этих «подфреймов» передаётся один за другим как аргумент вызываемой функции. Именно отсюда происходит термин «split-apply-combine»: разбить данные по группам, выполнить расчёт для каждой группы и объединить их в некую агрегированную форму. Если вам трудно представить, как именно будут выглядеть группы, просто итерации и печать нескольких из них могут быть очень полезны.
7. Используйте этот трюк с отображением для бининга
Представьте: есть Series и соответствующая «таблица сопоставления», где каждое значение принадлежит к многочленной группе или вообще не принадлежит ни одной группе:
Другими словами, вам нужно сопоставить countries со следующим результатом:
Здесь нужна функция, похожая на функцию Pandas pd.cut() , но для группировки на основе категориальной принадлежности. Для имитации можно воспользоваться pd.Series.map() , который вы уже видели:
Код значительно быстрее, чем вложенный цикл Python по группам для каждой страны:
Разберёмся, что происходит. Это отличный момент, чтобы войти в область видимости функции с помощью отладчика Python, pdb , чтобы проверить, какие переменные локальны относительно функции.
Задача — сопоставить каждую группу в groups целому числу. Однако Series.map() не распознаёт ‘ab’ — ему нужна разбитая версия, где каждый символ из каждой группы отображён на целое число. Это делается охватом словаря:
Этот словарь может передаваться в s.map() для сопоставления или «перевода» его значений в соответствующие индексы групп.
8. Загрузка данных из буфера обмена
Часто возникает ситуация, когда нужно передать данные из такого места, как Excel или Sublime Text, в структуру данных Pandas. В идеале сделать это хочется, не проходя промежуточный этап сохранения данных в файл и последующего чтения файла в Pandas. Вы можете загрузить DataFrames из буфера обмена компьютера с помощью pd.read_clipboard() . Его аргументы в виде ключевых слов передаются в pd.read_table() .
Это позволяет копировать структурированный текст непосредственно в DataFrame или Series. В Excel данные будут выглядеть примерно так:
Его текстовое представление может выглядеть так:
Просто выделите и скопируйте текст выше и вызовите pd.read_clipboard() :
9. Запись объектов Pandas в сжатый формат
Этот короткий пример завершает список. Начиная с версии Pandas 0.21.0 вы можете записывать объекты Pandas непосредственно для сжатия gzip, bz2, zip или xz, а не хранить несжатый файл в памяти и преобразовывать его. Вот пример, использующий данные abalone из первого трюка:
Коэффициент разницы в размерах равен 11,6:
Data Science — это не только статистика, но и написание кода, который с учётом работы с большими данными должен быть эффективным. В этом одна из причин высокой зарплаты специалиста в науке о данных, стать которым мы можем помочь вам на нашем курсе. Также вы можете узнать, как начать карьеру аналитика или инженера данных, начать с нуля или прокачаться в других направлениях, например, в Fullstack-разработке на Python: