2016-06-23 11 views
0

Ich bin neu in Python und möchte Data Wrangling-Prozess mit ihm lernen. Ich benutze Jupyter dafür.Wie man zufällige Probe einer cvs Akte in Python nimmt?

Ich habe eine Datei namens fle mit 81.000 Zeilen und 89 Spalten. Ich möchte nach dem Zufallsprinzip ungefähr 100 Zeilen davon auswählen. Wie mache ich das? Ich bekomme weiterhin folgenden Fehler.

fle=pd.read_csv("C:\Users\Mine\Documents\ssample.csv", low_memory= False) 
import random 
sampl = random.sample(fle, 10) 

Fehler, die ich erhalte ist:

IndexError        Traceback (most recent call last) 
<ipython-input-37-fa4ec429f883> in <module>() 
     1 import random 
     2 #To take a sample of 10000 samples 
----> 3 sampl = random.sample(fle, 10) 
     4 #pd.DataFrame(sampler).head(10) 

    C:\Users\E061921\AppData\Local\Continuum\Anaconda\lib\random.pyc in sample(self, population, k) 
334    for i in xrange(k):   # invariant: non-selected at [0,n-i) 
335     j = _int(random() * (n-i)) 
--> 336     result[i] = pool[j] 
337     pool[j] = pool[n-i-1] # move non-selected item into vacancy 
338   else: 

IndexError: list index out of range 
+1

Nur numpy die Nutzung zu handhaben [random.choice] (http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/ numpy.random.choice.html # numpy.random.choice) auf '' 'np.arange (number_of_rows, replace = False)' '' & indizieren Sie dann Ihren Datenrahmen wie in [hier] beschrieben durch iloc (http: // stackoverflow. com/questions/16096627/pandas-Wählen-Reihe-von-Daten-Frame-by-Integer-Index). – sascha

Antwort

1

Verwendung random.choice anstelle der Probe. Sie können csv.DictReader verwenden, um die csv als eine Liste von dicts

import csv 
import random 

random_rows = set() 
with open("C:\Users\Mine\Documents\ssample.csv", "r") as csvfile: 
    reader = csv.DictReader(csvfile) 

rows = [r for r in reader] 
while len(random_rows) < 100: 
    random_rows.add(random.choice(rows)) 
+0

Vielen Dank. Ich schätze unsere Hilfe sehr. –

Verwandte Themen