Pandas: Muestreo de un DataFrame [duplicado]


Esta pregunta ya tiene una respuesta aquí:

Estoy tratando de leer un archivo CSV bastante grande con Pandas y dividirlo en dos trozos aleatorios, uno de los cuales es el 10% de los datos y el otro es el 90%.

Aquí está mi intento actual:

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]

Para algunos reason, sklearn arroja este error cuando intento usar uno de estos objetos DataFrame resultantes dentro de un clasificador SVM:

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

Creo que lo estoy haciendo mal. ¿Hay una mejor manera de hacer esto?

Author: Blender, 2012-08-30

5 answers

¿Qué versión de pandas estás usando? Para mí tu código funciona bien (estoy en git master).

Otro enfoque podría ser:

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)

La versión más reciente (desde 0.16.1 en adelante) soporta esto directamente: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html

 77
Author: Wouter Overmeire,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-19 06:17:16

He encontrado que np.random.choice() nuevo en NumPy 1.7.0 funciona bastante bien para esto.

Por ejemplo, puede pasar los valores de índice de un DataFrame y el entero 10 para seleccionar 10 filas muestreadas uniformemente al azar.

rows = np.random.choice(df.index.values, 10)
sampled_df = df.ix[rows]
 79
Author: dragoljub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-18 14:41:39

Nuevo en la versión 0.16.1:

sample_dataframe = your_dataframe.sample(n=how_many_rows_you_want)

Doc aquí: http://pandas.pydata.org/pandas-docs/version/0.17.0/generated/pandas.DataFrame.sample.html

 21
Author: dval,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-26 15:52:39

Los Pandas 0.16.1 tienen un método sample para eso.

 14
Author: hurrial,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-22 03:13:46

Si estás usando pandas.read_csv puede muestrear directamente al cargar los datos, utilizando el parámetro skiprows. Aquí hay un breve artículo que he escrito sobre esto - https://nikolaygrozev.wordpress.com/2015/06/16/fast-and-simple-sampling-in-pandas-when-loading-data-from-files/

 6
Author: Nikolay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-16 07:03:17