ProgramingTip

Pandas : DataFrame 샘플링

bestdevel 2020. 11. 6. 19:02
반응형

Pandas : DataFrame 샘플링


Pandas는 상당히 큰 CSV 파일을 읽고 두 개의 임의의 청크로 분할합니다. 하나는 데이터의 10 %이고 다른 하나는 90 %입니다.

내 현재 시도는 다음과 달라집니다.

rows = data.index
row_count = len(rows)
random.shuffle(list(rows))

data.reindex(rows)

training_data = data[row_count // 10:]
testing_data = data[:row_count // 10]

어떤 버전의 sklearnSVM 분류기 내부에서 기존 결과 DataFrame 개체 중 하나를 사용하려고합니다.

IndexError: each subindex must be either a slice, an integer, Ellipsis, or newaxis

내가 잘못하고 많이 생각합니다. 이 작업을 수행하는 더 좋은 방법이 있습니까?


어떤 버전의 팬더를 사용하고 있습니까? 나를 위해 당신의 코드는 잘 작동합니다 (나는 git master에 있습니다).

또 다른 접근 방식은 다음과 가변적입니다.

In [117]: import pandas

In [118]: import random

In [119]: df = pandas.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))

In [120]: rows = random.sample(df.index, 10)

In [121]: df_10 = df.ix[rows]

In [122]: df_90 = df.drop(rows)

최신 버전 (0.16.1 이상) 은이를 직접 지원합니다 : http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html


나는 np.random.choice()NumPy 1.7.0의 새로운 기능이 이것에 대해 아주 잘 작동 한다는 것을 발견했습니다 .

예를 들어 DataFrame의 보안 값과 10을 전달하여 무작위로 샘플링 된 무작위 행 10 개를 선택할 수 있습니다.

rows = np.random.choice(df.index.values, 10)
sampled_df = df.ix[rows]

버전 0.16.1의 새로운 기능 :

sample_dataframe = your_dataframe.sample(n=how_many_rows_you_want)

여기에 문서 : http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html


Pandas 0.16.1에는 이에 대한 샘플 방법이 있습니다.


pandas.read_csv를 사용하는 경우 skiprows 매개 변수를 사용하여 데이터를로드 할 때 직접 샘플링 할 수 있습니다. 여기에 내가 쓰는 짧은 기사가 있습니다 -https : //nikolaygrozev.wordpress.com/2015/06/16/fast-and-simple-sampling-in-pandas-when-loading-data-from-files/

참고 URL : https://stackoverflow.com/questions/12190874/pandas-sampling-a-dataframe

반응형