programing

대형 판다 데이터 프레임 분할

iphone6s 2023. 7. 6. 21:57
반응형

대형 판다 데이터 프레임 분할

저는 423244줄의 큰 데이터 프레임을 가지고 있습니다.저는 이것을 4개로 나누고 싶습니다.제가 다음 코드를 시도했는데 오류가 발생했습니까? ValueError: array split does not result in an equal division

for item in np.split(df, 4):
    print item

이 데이터 프레임을 4개 그룹으로 분할하는 방법은 무엇입니까?

사용:

Docstring:
Split an array into multiple sub-arrays.

Please refer to the ``split`` documentation.  The only difference
between these functions is that ``array_split`` allows
`indices_or_sections` to be an integer that does *not* equally
divide the axis.
In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
   ...:                           'foo', 'bar', 'foo', 'foo'],
   ...:                    'B' : ['one', 'one', 'two', 'three',
   ...:                           'two', 'two', 'one', 'three'],
   ...:                    'C' : randn(8), 'D' : randn(8)})

In [3]: print df
     A      B         C         D
0  foo    one -0.174067 -0.608579
1  bar    one -0.860386 -1.210518
2  foo    two  0.614102  1.689837
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468

In [4]: import numpy as np
In [5]: np.array_split(df, 3)
Out[5]: 
[     A    B         C         D
0  foo  one -0.174067 -0.608579
1  bar  one -0.860386 -1.210518
2  foo  two  0.614102  1.689837,
      A      B         C         D
3  bar  three -0.284792 -1.071160
4  foo    two  0.843610  0.803712
5  bar    two -1.514722  0.870861,
      A      B         C         D
6  foo    one  0.131529 -0.968151
7  foo  three -1.002946 -0.257468]

저도 그렇게 하고 싶었습니다. 처음에는 분할 기능에 문제가 있었고, 그 다음에는 판다 0.15.2를 설치하는 데 문제가 있었습니다. 그래서 저는 예전 버전으로 돌아가서 아주 잘 작동하는 작은 기능을 썼습니다.이것이 도움이 되기를 바랍니다!

# input - df: a Dataframe, chunkSize: the chunk size
# output - a list of DataFrame
# purpose - splits the DataFrame into smaller chunks
def split_dataframe(df, chunk_size = 10000): 
    chunks = list()
    num_chunks = len(df) // chunk_size + 1
    for i in range(num_chunks):
        chunks.append(df[i*chunk_size:(i+1)*chunk_size])
    return chunks

알아두시기 바랍니다.np.array_split(df, 3)데이터 프레임을 3개의 하위 데이터 프레임으로 분할하는 동안split_dataframe@elixir의 답변에 정의된 함수, 호출 시split_dataframe(df, chunk_size=3)데이터 프레임 분할 간격chunk_size

예:

와 함께np.array_split:

df = pd.DataFrame([1,2,3,4,5,6,7,8,9,10,11], columns=['TEST'])
df_split = np.array_split(df, 3)

...세 개의 하위 데이터 프레임이 있습니다.

df_split[0] # 1, 2, 3, 4
df_split[1] # 5, 6, 7, 8
df_split[2] # 9, 10, 11

와 함께split_dataframe:

df_split2 = split_dataframe(df, chunk_size=3)

...4개의 하위 데이터 프레임이 있습니다.

df_split2[0] # 1, 2, 3
df_split2[1] # 4, 5, 6
df_split2[2] # 7, 8, 9
df_split2[3] # 10, 11

제가 옳기를 바라며, 이것이 유용하기를 바랍니다.

이제 우리는 플레인을 사용할 수 있을 것 같습니다.iloc와 함께range이를 위하여

chunk_size = int(df.shape[0] / 4)
for start in range(0, df.shape[0], chunk_size):
    df_subset = df.iloc[start:start + chunk_size]
    process_data(df_subset)
    ....

목록 이해를 사용하여 한 줄로 이 작업을 수행할 수 있습니다.

n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]

주의:

np.array_splitnumpy-1.9.0에서는 작동하지 않습니다.체크아웃했습니다.1.8.1과 함께 작동합니다.

오류:

데이터 프레임에 'size' 특성이 없습니다.

저는 한 줄짜리 글을 좋아하기 때문에 @LucyDrops 답변이 저에게 적합합니다.

하지만, 한 가지 중요한 것이 있습니다: a를 추가하세요..copy()청크가 원본의 복사본이어야 하는 경우df부품:

chunks = [df[i:i+n].copy() for i in range(0,df.shape[0],n)]

그렇지 않으면 다음 경고를 받을 가능성이 높습니다.chunks(예: 루프):

A value is trying to be set on a copy of a slice from a DataFrame.

(자세한 내용은 Pandas 설명서 참조)

@elixir의 대답을 바탕으로...
메모리에 있는 모든 청크를 로드하지 않으려면 제너레이터를 사용하는 것이 좋습니다.

def chunkit(df, chunk_size = 10000): 
    num_chunks = len(df) // chunk_size
    if len(df) % chunk_size != 0:
        num_chunks += 1
    for i in range(num_chunks):
        yield df[i*chunk_size:(i + 1) * chunk_size]

사용할 수 있습니다.groupby정수 열거형 인덱스가 있다고 가정합니다.

import math
df = pd.DataFrame(dict(sample=np.arange(99)))
rows_per_subframe = math.ceil(len(df) / 4.)

subframes = [i[1] for i in df.groupby(np.arange(len(df))//rows_per_subframe)]

참고:groupby두 번째 요소가 데이터 프레임인 튜플을 반환하므로 추출이 약간 복잡합니다.

>>> len(subframes), [len(i) for i in subframes]
(4, [25, 25, 25, 24])

저도 경험했습니다.np.array_splitPandas DataFrame에서 작동하지 않습니다.제 솔루션은 데이터 프레임의 인덱스만 분할한 다음 "그룹" 레이블이 있는 새 열을 도입하는 것이었습니다.

indexes = np.array_split(df.index,N, axis=0)
for i,index in enumerate(indexes):
   df.loc[index,'group'] = i

이를 통해 각 그룹의 평균 값을 계산할 때와 같이 연산별 그룹화를 매우 편리하게 할 수 있습니다.

df.groupby(by='group').mean()

언급URL : https://stackoverflow.com/questions/17315737/split-a-large-pandas-dataframe

반응형