파이썬 팬더에서 열의 dtype을 확인하는 방법.
숫자 열과 문자열 열을 처리하려면 다른 함수를 사용해야 합니다.제가 지금 하는 일은 정말 바보같습니다.
allc = list((agg.loc[:, (agg.dtypes==np.float64)|(agg.dtypes==np.int)]).columns)
for y in allc:
treat_numeric(agg[y])
allc = list((agg.loc[:, (agg.dtypes!=np.float64)&(agg.dtypes!=np.int)]).columns)
for y in allc:
treat_str(agg[y])
이것을 하는 더 우아한 방법이 있습니까?예.
for y in agg.columns:
if(dtype(agg[y]) == 'string'):
treat_str(agg[y])
elif(dtype(agg[y]) != 'string'):
treat_numeric(agg[y])
다음을 사용하여 열의 데이터 유형에 액세스할 수 있습니다.
for y in agg.columns:
if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):
treat_numeric(agg[y])
else:
treat_str(agg[y])
pandas 0.20.2수 있는 것은 다음과 같습니다.
from pandas.api.types import is_string_dtype
from pandas.api.types import is_numeric_dtype
is_string_dtype(df['A'])
>>>> True
is_numeric_dtype(df['B'])
>>>> True
코드는 다음과 같습니다.
for y in agg.columns:
if (is_string_dtype(agg[y])):
treat_str(agg[y])
elif (is_numeric_dtype(agg[y])):
treat_numeric(agg[y])
이것이 약간 오래된 스레드라는 것을 알지만 팬더 19.02를 사용하면 다음을 수행할 수 있습니다.
df.select_dtypes(include=['float64']).apply(your_function)
df.select_dtypes(exclude=['string','object']).apply(your_other_function)
http://pandas.pydata.org/pandas-docs/version/0.19.2/generated/pandas.DataFrame.select_dtypes.html
질문 제목은 일반적이지만 작성자는 질문 본문에 명시된 사용 사례가 구체적입니다.따라서 다른 답변을 사용할 수 있습니다.
그러나 제목 질문에 완전히 답하기 위해서는 모든 접근 방식이 경우에 따라 실패하고 약간의 재작업이 필요할 수 있음을 분명히 해야 합니다.저는 신뢰성 순서의 감소에 있어 (제 생각에는) 그 모든 것들을 검토했습니다.
을 통해 직접 ==(답변 없음).
이 답변이 받아들여지고 대부분의 찬성표가 있음에도 불구하고, 저는 이 방법을 전혀 사용해서는 안 된다고 생각합니다.왜냐하면 사실 이 접근법은 여기서 여러 번 언급했듯이 파이썬에서는 권장되지 않기 때문입니다.
하지만 여전히 사용하고 싶다면 - 다음과 같은 판다 특정 d형을 알아야 합니다.pd.CategoricalDType,pd.PeriodDtype또는pd.IntervalDtype의 여서여을사분기야합니다해용▁extra합을 사용해야 .type( )유형을 올바르게 인식하려면:
s = pd.Series([pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')])
s
s.dtype == pd.PeriodDtype # Not working
type(s.dtype) == pd.PeriodDtype # working
>>> 0 2002-03-01
>>> 1 2012-02-01
>>> dtype: period[D]
>>> False
>>> True
여기서 또 다른 경고는 유형을 정확하게 지적해야 한다는 것입니다.
s = pd.Series([1,2])
s
s.dtype == np.int64 # Working
s.dtype == np.int32 # Not working
>>> 0 1
>>> 1 2
>>> dtype: int64
>>> True
>>> False
2. isinstance()접근.
이 방법은 지금까지 답변에서 언급되지 않았습니다.
것이 - 이 즉 - 따유직비아것접생니면 - 를내파함이썬수다위장 - 이즉사보니습겠, - 용해라된해을라적형서을목이각은는교좋이하▁for▁function▁built-.isinstance().
가 어떤 있다고 하지만, 우가어물가있가때기문에정하, 그것단처실니다합패음에지은리다고떤지체고를▁it▁just다,▁fails▁assumes니,실합패▁that▁but▁beginning▁in.pd.Series또는pd.DataFrame사전 정의된 빈 용기로 사용할 수 있습니다.dtype하지만 그 안에 물체가 없습니다.
s = pd.Series([], dtype=bool)
s
>>> Series([], dtype: bool)
그러나 이 문제를 어떻게든 극복하고 각 개체에 액세스하려면, 예를 들어 첫 번째 행에서 다음과 같이 dtype을 확인합니다.
df = pd.DataFrame({'int': [12, 2], 'dt': [pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')]},
index = ['A', 'B'])
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (dtype('int64'), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
단일 열에 데이터 유형이 혼합된 경우에는 오해의 소지가 있습니다.
df2 = pd.DataFrame({'data': [12, pd.Timestamp('2013-01-02')]},
index = ['A', 'B'])
for col in df2.columns:
df2[col].dtype, 'is_int64 = %s' % isinstance(df2.loc['A', col], np.int64)
>>> (dtype('O'), 'is_int64 = False')
은 - 이 으로 인식할 수 없다는 것입니다.Categorydtype. 문서에 명시된 대로:
범주형 데이터에서 단일 항목을 반환하면 길이가 "1"인 범주형이 아닌 값도 반환됩니다.
df['int'] = df['int'].astype('category')
for col in df.columns:
df[col].dtype, 'is_int64 = %s' % isinstance(df.loc['A', col], np.int64)
>>> (CategoricalDtype(categories=[2, 12], ordered=False), 'is_int64 = True')
>>> (dtype('<M8[ns]'), 'is_int64 = False')
그래서 이 방법 또한 거의 적용되지 않습니다.
3. df.dtype.kind접근.
은 빈 이 는 비 수 있 니 습 다 있 을 메 어 아 서 드 직 ▁empty 다 ▁with ▁work 니 ▁this ▁may ▁yet 있 ▁method 습 이수 있pd.Series또는pd.DataFrames하지만 또 다른 문제가 있습니다.
첫 번째 - 일부 d 유형은 다를 수 없습니다.
df = pd.DataFrame({'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'str' :['s1', 's2'],
'cat' :[1, -1]})
df['cat'] = df['cat'].astype('category')
for col in df:
# kind will define all columns as 'Object'
print (df[col].dtype, df[col].dtype.kind)
>>> period[D] O
>>> object O
>>> category O
두 번째로, 저에게 여전히 불분명한 것은 심지어 일부 dtype None에서도 반환됩니다.
4. df.select_dtypes접근.
이것이 우리가 거의 원하는 것입니다.이 방법은 판다 내부에서 설계되어 앞에서 언급한 대부분의 코너 케이스(빈 데이터 프레임, numpy 또는 판다별 dtype)를 잘 처리합니다.단일 dtype과 같이 잘 작동합니다..select_dtypes('bool')dtype을 기준으로 열 할 수 .
test = pd.DataFrame({'bool' :[False, True], 'int64':[-1,2], 'int32':[-1,2],'float': [-2.5, 3.4],
'compl':np.array([1-1j, 5]),
'dt' :[pd.Timestamp('2013-01-02'), pd.Timestamp('2016-10-20')],
'td' :[pd.Timestamp('2012-03-02')- pd.Timestamp('2016-10-20'),
pd.Timestamp('2010-07-12')- pd.Timestamp('2000-11-10')],
'prd' :[pd.Period('2002-03','D'), pd.Period('2012-02-01', 'D')],
'intrv':pd.arrays.IntervalArray([pd.Interval(0, 0.1), pd.Interval(1, 5)]),
'str' :['s1', 's2'],
'cat' :[1, -1],
'obj' :[[1,2,3], [5435,35,-52,14]]
})
test['int32'] = test['int32'].astype(np.int32)
test['cat'] = test['cat'].astype('category')
문서에 명시된 바와 같이 다음과 같습니다.
test.select_dtypes('number')
>>> int64 int32 float compl td
>>> 0 -1 -1 -2.5 (1-1j) -1693 days
>>> 1 2 2 3.4 (5+0j) 3531 days
여기서 우리는 처음으로 예상치 못한 결과를 보게 될 것이라고 생각할 수 있습니다. 질문입니다.TimeDelta는 출력에 됩니다.DataFrame하지만 반대로 대답했듯이, 그것은 그렇게 되어야 하지만, 사람들은 그것을 인식해야 합니다.참고:booldtype은 건너뛰고, 그것은 또한 누군가에게 원하지 않을 수 있지만, 그것은 때문입니다.bool그리고.number서로 다른 numpyd 유형의 "트리"에 있습니다.쿨의 경우, 우리는 사용할 수 있습니다.test.select_dtypes(['bool'])여기서.
의 경우 코드가 : 이방법다음제현사판버다재항전 (0.24.2)의다다니.test.select_dtypes('period')올릴 것입니다NotImplementedError.
그리고 또 다른 점은 문자열이 다른 개체와 다를 수 없다는 것입니다.
test.select_dtypes('object')
>>> str obj
>>> 0 s1 [1, 2, 3]
>>> 1 s2 [5435, 35, -52, 14]
하지만 이것은 첫 번째입니다 - 문서에 이미 언급되어 있습니다.그리고 두 번째는 이 방법의 문제가 아니라 문자열이 저장되는 방식입니다.DataFrame어쨌든 이 사건은 사후 처리가 필요합니다.
5. df.api.types.is_XXX_dtype접근.
이것은 제가 생각하는 것처럼 유형 인식(기능이 있는 모듈의 경로 자체를 말합니다)을 달성하기 위한 가장 강력하고 기본적인 방법입니다.그리고 그것은 거의 완벽하게 작동하지만, 여전히 적어도 하나의 경고가 있고 여전히 어떻게든 문자열 열을 구별해야 합니다.
게다가, 이것은 주관적일 수 있지만, 이 접근법은 또한 더 '인간이 이해할 수 있는' 것을 가지고 있습니다.number 그룹 를 dtypes와 한 결과.select_dtypes('number'):
for col in test.columns:
if pd.api.types.is_numeric_dtype(test[col]):
print (test[col].dtype)
>>> bool
>>> int64
>>> int32
>>> float64
>>> complex128
아니요.timedelta그리고.bool포함됩니다.완벽하네요.
제 파이프라인은 현재 이 기능과 약간의 사후 처리 기능을 정확히 활용합니다.
산출량.
논의된 모든 접근법이 사용될 수 있지만, 적용 가능한 접근법으로만 고려되어야 한다는 요점을 주장할 수 있기를 바랍니다.
데이터 프레임 열의 유형을 문자열로 표시하려면 다음 작업을 수행합니다.
df['A'].dtype.kind
예:
In [8]: df = pd.DataFrame([[1,'a',1.2],[2,'b',2.3]])
In [9]: df[0].dtype.kind, df[1].dtype.kind, df[2].dtype.kind
Out[9]: ('i', 'O', 'f')
코드에 대한 답:
for y in agg.columns:
if(agg[y].dtype.kind == 'f' or agg[y].dtype.kind == 'i'):
treat_numeric(agg[y])
else:
treat_str(agg[y])
참고:
uint그리고.UInt한 사람들u하지i.- dtype 검사 유틸리티 기능(예:
열 데이터 유형을 인쇄하는 방법
예를 들어 파일에서 가져오기 후 데이터 유형을 확인하려면 다음과 같이 하십시오.
def printColumnInfo(df):
template="%-8s %-30s %s"
print(template % ("Type", "Column Name", "Example Value"))
print("-"*53)
for c in df.columns:
print(template % (df[c].dtype, c, df[c].iloc[1]) )
출력 예시:
Type Column Name Example Value
-----------------------------------------------------
int64 Age 49
object Attrition No
object BusinessTravel Travel_Frequently
float64 DailyRate 279.0
언급URL : https://stackoverflow.com/questions/22697773/how-to-check-the-dtype-of-a-column-in-python-pandas
'code' 카테고리의 다른 글
| Excel 상태 표시줄을 팝업하시겠습니까? (0) | 2023.06.22 |
|---|---|
| 외부 키를 사용하여 .xls 파일을 .sql로 가져오는 방법 (0) | 2023.06.22 |
| gitgrep 검색에서 특정 디렉터리/파일을 제외하는 방법 (0) | 2023.06.22 |
| PowerShell에서 "@" 기호는 무엇을 합니까? (0) | 2023.06.22 |
| Oracle 오류: ORA-00905:키워드 누락 (0) | 2023.06.17 |