[python] 큰 팬더 데이터 프레임 분할

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

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

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



답변

사용 np.array_split:

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


답변

이제 우리는 이것을 위해 plain ilocwith 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)
    ....


답변

그주의 np.array_split(df, 3)그동안 3 하위 dataframes에 dataframe 분할 split_dataframe기능에 정의 된 @ 불로 불사의 영약의 대답 이라 할 때, split_dataframe(df, chunk_size=3)모든 dataframe을 분할 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)

… 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

내가 옳고 이것이 유용하기를 바랍니다.


답변

주의:

np.array_splitnumpy-1.9.0에서는 작동하지 않습니다. 나는 체크 아웃 : 1.8.1에서 작동합니다.

오류:

데이터 프레임에는 ‘크기’속성이 없습니다.


답변

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])


답변

또한 Pandas DataFrame에서 작동하지 않는 np.array_split을 경험했습니다. 내 솔루션은 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()