본문 바로가기
파이썬

파이썬 Pandas로 CSV를 읽는 동안 열 유형 설정

by º기록 2020. 11. 7.
반응형

다음 형식으로 csv 파일을 pandas 데이터 프레임으로 읽으려고합니다.

dp = pd.read_csv('products.csv', header = 0,  dtype = {'name': str,'review': str,
                                                      'rating': int,'word_count': dict}, engine = 'c')
print dp.shape
for col in dp.columns:
    print 'column', col,':', type(col[0])
print type(dp['rating'][0])
dp.head(3)

다음은 출력입니다.

(183531, 4)
column name : <type 'str'>
column review : <type 'str'>
column rating : <type 'str'>
column word_count : <type 'str'>
<type 'numpy.int64'>



그건 그렇고, 엔진이나 헤더를 지정하지 않는 것과 같은 조정은 아무것도 변경하지 않습니다.

감사합니다.

 

해결 방법

 

루프에서 다음을 수행합니다.

for col in dp.columns:
    print 'column', col,':', type(col[0])

col [0] 은 문자열 인 열 이름의 첫 글자이기 때문에 모든 곳에서 출력으로 str 을 올바르게 볼 수 있습니다.

예를 들어,이 루프를 실행하면 :

for col in dp.columns:
    print 'column', col,':', col[0]

각 열 이름 문자열의 첫 글자가 출력되는 것을 볼 수 있습니다. 이것이 col [0] 입니다.

루프는 시리즈 데이터 가 아닌 열 이름 에서만 반복됩니다.

정말로 원하는 것은 루프에서 각 열의 데이터 유형 (헤더 또는 헤더의 일부가 아님)을 확인하는 것입니다.

따라서 열 데이터 (헤더가 아닌 데이터)의 유형을 가져 오려면 대신 이렇게하십시오.

for col in dp.columns:
    print 'column', col,':', type(dp[col][0])

이것은 rating 열의 유형을 개별적으로 인쇄 할 때 수행 한 것과 유사합니다.

 

참조 페이지 https://stackoverflow.com/questions/36195485

 

 

반응형

댓글