source

Panda read_csv: low_memory 및 dtype

goodcode 2022. 9. 23. 00:13
반응형

Panda read_csv: low_memory 및 dtype

df = pd.read_csv('somefile.csv')

...오류 표시:

.../site-barning/varning/io/parsers.py:1130: DtypeWarning: 컬럼(4,5,7,16)에 혼합된 유형이 있습니다.Import 시 dtype 옵션을 지정하거나 low_memory=False를 설정합니다.

?이 되는 거죠?dtype low_memory왜 「」가 되는가?low_memory=False

권장되지 않는 low_memory 옵션

low_memory옵션은 적절하게 권장되지 않지만 실제로는 아무것도 하지 않기 때문에 권장되어야 합니다.

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★low_memorywarning은 각 컬럼의 dtype을 추측하는 것은 메모리를 필요로 하기 때문입니다.판다는 각 열의 데이터를 분석하여 어떤 dtype을 설정할지 결정하려고 합니다.

Dtype 추측(매우 불량)

판다는 전체 파일을 읽은 후에야 기둥의 dtype을 결정할 수 있다.즉, 마지막 값을 읽을 때 해당 열의 dtype을 변경해야 하는 위험이 없는 한 파일 전체를 읽기 전에 실제로 구문 분석할 수 없습니다.

user_id라는 이름의 열이 있는 파일의 예를 생각해 보겠습니다.여기에는 user_id가 항상 숫자인 1000만 행이 포함됩니다.판다는 그것이 숫자라는 것을 알 수 없기 때문에, 그것은 아마도 전체 파일을 읽을 때까지 원래의 문자열로 유지할 것이다.

dtype 지정(항상 수행해야 함)

추가

dtype={'user_id': int}

판다가 파일을 읽기 시작하면, 이것은 정수일 뿐이라는 것을 알게 될 것입니다.

또한 파일의 마지막 행이 다음과 같은 경우 주의할 필요가 있습니다."foobar"에 기재되어 있다.user_id을을 dtype 。

dtype을 정의하면 파손되는 데이터의 예

import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO


csvdata = """user_id,username
1,Alice
3,Bob
foobar,Caesar"""
sio = StringIO(csvdata)
pd.read_csv(sio, dtype={"user_id": int, "username": "string"})

ValueError: invalid literal for long() with base 10: 'foobar'

dtypes는 보통 numpy한 것입니다.자세한 내용은 http://docs.scipy.org/doc/numpy/reference/generated/numpy.dtype.html를 참조해 주세요.

어떤 dtype이 있습니까?

numpy dtype: float, int, bool, timedelta64[ns] 및 datetime64[ns]에 액세스 할 수 있습니다.numpy date/time dtype은 시간대를 인식하지 않습니다.

판다는 이 D타입 세트를 자신의 것으로 확장합니다.

'datetime64[ns, <tz>]'이치노

기본적으로 열거형인 'category'(저장할 정수 키로 표시되는 항목)

'period[]' timedelta와 혼동하지 마십시오. 이러한 개체는 실제로 특정 기간에 고정됩니다.

'Sparse', 'Sparse[int]', 'Sparse[float]'는 스파스 데이터 또는 '구멍이 많은 데이터'를 위한 것입니다. NaN 또는 None을 데이터 프레임에 저장하는 대신 개체를 생략하여 공간을 절약합니다.

'Interval'은 자체 주제이지만 인덱싱에 주로 사용됩니다.자세한 것은 이쪽

'Int8', 'Int16', 'Int32', 'Int64', 'UINT8', 'UINT16', 'UINT32', 'UINT64'는 모두 숫자 변형과 달리 무효인 판다 고유의 정수이다.

으로 문자열에 수 ..str속성을 지정합니다.

'bool'은 숫자 'bool'과 비슷하지만 누락된 데이터를 지원합니다.

자세한 내용은 여기를 참조하십시오.

팬더 dtype 참조

Gotchas, 경고, 메모

★★dtype=object위의 경고는 무시되지만 메모리 효율은 향상되지 않습니다.이치노

★★dtype=unicode안 할 거예요. '아까운이 ''이 . 왜냐하면 멍해질 때까지unicode합니다.object.

변환기 사용방법

@pander는 팬더와 마주쳤을 때 폭발하는 것을 방지하기 위해 컨버터 사용을 정확하게 지적하고 있다.'foobar'「 「 」로 int변환기는 판다에게 매우 무겁고 비효율적이기 때문에 최후의 수단으로 사용해야 한다는 것을 덧붙이고 싶습니다.read_csv 프프프 ____ 。

CSV 파일은 한 줄씩 처리할 수 있기 때문에 파일을 세그먼트로 잘라 여러 프로세스를 실행하는 것만으로 여러 변환기에서 병렬로 보다 효율적으로 처리할 수 있습니다.이것은, 팬더가 서포트하고 있지 않습니다.하지만 이건 다른 이야기야.

시험:

dashboard_df = pd.read_csv(p_file, sep=',', error_bad_lines=False, index_col=False, dtype='unicode')

팬더 문서에 따르면:

dtype : 이름 또는 dit 컬럼 -> 타입을 입력합니다.

low_memory에 대해서는 기본적으로 True이며 아직 문서화되지 않았습니다.나는 그것이 관련이 있다고 생각하지 않는다.이 오류 메시지는 일반적이므로 low_memory를 조작할 필요가 없습니다.이것이 도움이 되기를 바라며, 더 문제가 있으면 알려주세요.

df = pd.read_csv('somefile.csv', low_memory=False)

이것으로 문제가 해결됩니다.CSV에서 180만 행을 읽었을 때도 똑같은 오류가 발생했습니다.

앞서 firelynx에서 설명한 바와 같이 dtype이 명시적으로 지정되어 있고 dtype과 호환되지 않는 혼합 데이터가 있는 경우 로딩이 크래시됩니다.이러한 변환기를 사용하여 호환되지 않는 데이터 유형의 값을 변경하여 데이터를 계속 로드할 수 있도록 했습니다.

def conv(val):
    if not val:
        return 0    
    try:
        return np.float64(val)
    except:        
        return np.float64(0)

df = pd.read_csv(csv_file,converters={'COL_A':conv,'COL_B':conv})

나한텐 효과가 있었어!

file = pd.read_csv('example.csv', engine='python')

대용량 csv 파일(600만 행)을 처리할 때도 비슷한 문제가 있었습니다.세 가지 문제가 있었습니다.

  1. 파일에 이상한 문자가 포함되어 있습니다(부호화 사용).
  2. 데이터 형식이 지정되지 않았습니다(dtype 속성을 사용하여 검색됨).
  3. 상기의 사용법을 사용해도, 파일명에 근거해 정의할 수 없는 file_format 관련의 문제에 직면했습니다(try 를 사용해 수정).제외..)
    df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
                     names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
                     dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
    
    try:
        df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
    except:
        df['file_format'] = ''

저는 그게 잘 먹혔어요.low_memory = False데이터 프레임 Import 중.이것이 나에게 효과가 있었던 모든 변화입니다.

df = pd.read_csv('export4_16.csv',low_memory=False)

팬더 문서에 따르면,low_memory=False이라면engine='c'(기본값)이 이 문제에 대한 합리적인 해결책입니다.

한다면low_memory=False컬럼 전체를 먼저 읽은 후 적절한 유형을 결정합니다.예를 들어, 컬럼은 정보를 보존하기 위해 필요에 따라 오브젝트(스트링)로 유지됩니다.

한다면low_memory=True(기본값) 판다는 데이터를 줄 단위로 읽은 다음 함께 추가합니다.그러면 청크 판다들이 정수로 주조할 수 없는 것을 발견했는지 여부에 따라 일부 기둥은 정수와 끈이 뒤섞인 덩어리처럼 보일 수 있다.나중에 문제가 발생할 수 있습니다.경고는 이 문제가 적어도 한 번 읽었을 때 발생했음을 알려 주므로 주의해야 합니다.설정low_memory=False는 메모리를 더 많이 사용하지만 문제를 회피합니다.

는 ★★★★★★★★★★★★★★★★★★★★★★★★」low_memory=True디폴트는 나쁘지만 대규모 데이터 세트보다 소규모 데이터 세트를 많이 사용하는 영역에서 작업하고 있기 때문에 효율성보다 편리성이 더 중요합니다.

는 ' 낫다'의 예를 .low_memory=True설정이 되어 있고 컬럼에 혼합 타입이 들어갑니다.은 @@firelynx로 냅니다.

import pandas as pd
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

# make a big csv data file, following earlier approach by @firelynx
csvdata = """1,Alice
2,Bob
3,Caesar
"""

# we have to replicate the "integer column" user_id many many times to get
# pd.read_csv to actually chunk read. otherwise it just reads 
# the whole thing in one chunk, because it's faster, and we don't get any 
# "mixed dtype" issue. the 100000 below was chosen by experimentation.
csvdatafull = ""
for i in range(100000):
    csvdatafull = csvdatafull + csvdata
csvdatafull =  csvdatafull + "foobar,Cthlulu\n"
csvdatafull = "user_id,username\n" + csvdatafull

sio = StringIO(csvdatafull)
# the following line gives me the warning:
    # C:\Users\rdisa\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3072: DtypeWarning: Columns (0) have mixed types.Specify dtype option on import or set low_memory=False.
    # interactivity=interactivity, compiler=compiler, result=result)
# but it does not always give me the warning, so i guess the internal workings of read_csv depend on background factors
x = pd.read_csv(sio, low_memory=True) #, dtype={"user_id": int, "username": "string"})

x.dtypes
# this gives:
# Out[69]: 
# user_id     object
# username    object
# dtype: object

type(x['user_id'].iloc[0]) # int
type(x['user_id'].iloc[1]) # int
type(x['user_id'].iloc[2]) # int
type(x['user_id'].iloc[10000]) # int
type(x['user_id'].iloc[299999]) # str !!!! (even though it's a number! so this chunk must have been read in as strings)
type(x['user_id'].iloc[300000]) # str !!!!!

가 되고 있는 경우(또, 이것을 를 예로 들면, 「」를 했다고 가정해 .「 。pd.read_csv()그런 다음 식별자에 따라 중복된 파일을 삭제하려고 합니다.식별자가 숫자일 때도 있고 문자열일 때도 있다고 합니다.은 '일 수 있습니다.이치노

★★★★★★★★★★★★★★★★ low_memory=True판다는 식별란에서 다음과 같이 읽을 수 있다.

81287
81287
81287
81287
81287
"81287"
"81287"
"81287"
"81287"
"97324-32"
"97324-32"
"97324-32"
"97324-32"
"97324-32"

단지 무언가를 뭉치거나 해서 식별자 81287이 숫자이거나 문자열일 수도 있습니다.이걸 근거로 중복을 없애려고 하면

81287 == "81287"
Out[98]: False

있듯이, 「」, 「」를 는, .read_csv()그래서이렇게 돼요.

file = pd.read_csv('example.csv', dtype='unicode')

때때로, 다른 모든 것이 실패했을 때, 여러분은 판다들에게 그것에 대해 입 다물라고 말하고 싶을 것입니다.

# Ignore DtypeWarnings from pandas' read_csv                                                                                                                                                                                            
warnings.filterwarnings('ignore', message="^Columns.*")

약 400MB의 파일에 대해서도 비슷한 문제가 있었습니다. ★★low_memory=False프레임이 한 후 계속 진행합니다먼저 간단한 작업을 수행하십시오. 계속하기 전에 데이터 프레임이 시스템 메모리보다 크지 않은지 확인하고 재부팅한 다음 RAM을 지웁니다.남아 있다면 꼭해 볼 가 있습니다..csv파일은 정상입니다.Excel excel excel excel excel excel excel excel excel excel excel excel excel excel excel excel excel excel excel 。원래 데이터가 깨지면 대혼란을 일으킬 수 있어

Jerald Achaibar의 답변을 바탕으로 혼합된 Dytpes 경고를 검출할 수 있으며 경고가 발생했을 때만 속도가 느린 python 엔진을 사용할 수 있습니다.

import warnings

# Force mixed datatype warning to be a python error so we can catch it and reattempt the 
# load using the slower python engine
warnings.simplefilter('error', pandas.errors.DtypeWarning)
try:
    df = pandas.read_csv(path, sep=sep, encoding=encoding)
except pandas.errors.DtypeWarning:
    df = pandas.read_csv(path, sep=sep, encoding=encoding, engine="python")

언급URL : https://stackoverflow.com/questions/24251219/pandas-read-csv-low-memory-and-dtype-options

반응형