program story

dtype ( 'O')은 무엇입니까?

inputbox 2020. 10. 30. 08:00
반응형

dtype ( 'O')은 무엇입니까?


팬더에 데이터 프레임이 있고 그 값의 유형이 무엇인지 알아 내려고 노력하고 있습니다. 열 유형이 무엇인지 잘 모르겠습니다 'Test'. 그러나 실행 myFrame['Test'].dtype하면을 얻습니다.

dtype('O')

이것은 무엇을 의미 하는가?


그 뜻은:

'O'     (Python) objects

소스 .

첫 번째 문자는 데이터 종류를 지정하고 나머지 문자는 항목 당 바이트 수를 지정합니다. 단, 유니 코드는 문자 수로 해석됩니다. 항목 크기는 기존 유형과 일치해야합니다. 그렇지 않으면 오류가 발생합니다. 지원되는 종류가 기존 종류에 해당하지 않으면 오류가 발생합니다. 지원되는 종류는 다음과 같습니다.

'b'       boolean
'i'       (signed) integer
'u'       unsigned integer
'f'       floating-point
'c'       complex-floating point
'O'       (Python) objects
'S', 'a'  (byte-)string
'U'       Unicode
'V'       raw data (void)

필요한 경우 또 다른 답변이 도움이됩니다 type.


이것은 "python 객체"를 의미합니다. 즉, numpy가 지원하는 내장 스칼라 유형 중 하나가 아닙니다.

np.array([object()]).dtype
=> dtype('O')

'O'는 객체를 나타 냅니다 .

#Loading a csv file as a dataframe
import pandas as pd 
train_df = pd.read_csv('train.csv')
col_name = 'Name of Employee'

#Checking the datatype of column name
train_df[col_name].dtype

#Instead try printing the same thing
print train_df[col_name].dtype

첫 번째 줄은 다음을 반환합니다. dtype('O')

print 문이있는 줄은 다음을 반환합니다. object


dtype('O')데이터 프레임 내부 를 볼 때 이것은 Pandas 문자열을 의미합니다.

무엇입니까 dtype?

pandas또는에 속하는 것 numpy또는 둘 다 또는 다른 것? 판다 코드를 살펴보면 :

df = pd.DataFrame({'float': [1.0],
                    'int': [1],
                    'datetime': [pd.Timestamp('20180310')],
                    'string': ['foo']})
print(df)
print(df['float'].dtype,df['int'].dtype,df['datetime'].dtype,df['string'].dtype)
df['string'].dtype

다음과 같이 출력됩니다.

   float  int   datetime string    
0    1.0    1 2018-03-10    foo
---
float64 int64 datetime64[ns] object
---
dtype('O')

마지막을 dtype('O')Python 유형 문자열 인 Pandas 또는 Pandas 객체 로 해석 할 수 있으며 이는 Numpy string_또는 unicode_유형에 해당합니다 .

Pandas dtype    Python type     NumPy type          Usage
object          str             string_, unicode_   Text

Don Quixote가 엉덩이에있는 것처럼 Pandas는 Numpy에 있고 Numpy는 시스템의 기본 아키텍처를 이해하고이를 위해 클래스 numpy.dtype를 사용합니다.

데이터 유형 객체는 다음을 포함 numpy.dtype하여 데이터 유형을 보다 정확하게 이해하는 클래스 의 인스턴스입니다 .

  • 데이터 유형 (정수, 부동 소수점, Python 객체 등)
  • 데이터의 크기 (예 : 정수의 바이트 수)
  • 데이터의 바이트 순서 (리틀 엔디안 또는 빅 엔디안)
  • 데이터 유형이 구조화 된 경우 다른 데이터 유형의 집합 (예 : 정수 및 부동 소수점으로 구성된 배열 항목 설명)
  • 구조의 "필드"이름은 무엇입니까?
  • 각 필드의 데이터 유형은 무엇입니까
  • 각 필드가 차지하는 메모리 블록 부분
  • 데이터 유형이 하위 배열 인 경우 그 모양과 데이터 유형은 무엇입니까?

이 질문의 맥락에서 dtypepands와 numpy 모두에 속하며 특히 dtype('O')우리가 문자열을 기대한다는 것을 의미합니다.


Here is some code for testing with explanation: If we have the dataset as dictionary

import pandas as pd
import numpy as np
from pandas import Timestamp

data={'id': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'date': {0: Timestamp('2018-12-12 00:00:00'), 1: Timestamp('2018-12-12 00:00:00'), 2: Timestamp('2018-12-12 00:00:00'), 3: Timestamp('2018-12-12 00:00:00'), 4: Timestamp('2018-12-12 00:00:00')}, 'role': {0: 'Support', 1: 'Marketing', 2: 'Business Development', 3: 'Sales', 4: 'Engineering'}, 'num': {0: 123, 1: 234, 2: 345, 3: 456, 4: 567}, 'fnum': {0: 3.14, 1: 2.14, 2: -0.14, 3: 41.3, 4: 3.14}}
df = pd.DataFrame.from_dict(data) #now we have a dataframe

print(df)
print(df.dtypes)

The last lines will examine the dataframe and note the output:

   id       date                  role  num   fnum
0   1 2018-12-12               Support  123   3.14
1   2 2018-12-12             Marketing  234   2.14
2   3 2018-12-12  Business Development  345  -0.14
3   4 2018-12-12                 Sales  456  41.30
4   5 2018-12-12           Engineering  567   3.14
id               int64
date    datetime64[ns]
role            object
num              int64
fnum           float64
dtype: object

All kind of different dtypes

df.iloc[1,:] = np.nan
df.iloc[2,:] = None

But if we try to set np.nan or None this will not affect the original column dtype. The output will be like this:

print(df)
print(df.dtypes)

    id       date         role    num   fnum
0  1.0 2018-12-12      Support  123.0   3.14
1  NaN        NaT          NaN    NaN    NaN
2  NaN        NaT         None    NaN    NaN
3  4.0 2018-12-12        Sales  456.0  41.30
4  5.0 2018-12-12  Engineering  567.0   3.14
id             float64
date    datetime64[ns]
role            object
num            float64
fnum           float64
dtype: object

So np.nan or None will not change the columns dtype, unless we set the all column rows to np.nan or None. In that case column will become float64 or object respectively.

You may try also setting single rows:

df.iloc[3,:] = 0 # will convert datetime to object only
df.iloc[4,:] = '' # will convert all columns to object

And to note here, if we set string inside a non string column it will become string or object dtype.

참고URL : https://stackoverflow.com/questions/37561991/what-is-dtypeo

반응형