Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to print random n rows from a csv file?

So i have a big csv file and my code prints all the rows but i want to print, for example, only 20 random rows from 100000 rows. I know that somehow with random.sample u can do that, but i don’t really know how. Any suggestions?

There is my code:

import csv

with open(r'Z:/datasets/room-segmentation/labeling/test_examples_doors/labels.csv') as csvfile:   
 data = csv.DictReader(csvfile)
 for row in data:
     if row['open']=='1':
print(row['image'], row['open'])

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I assume you want to randomly sample your data, rather than just take the first 20 rows?

In this case you can convert data to a list and then sample it:

import csv
import pandas as pd
import random
with open(r'Z:/datasets/room-segmentation/labeling/test_examples_doors/labels.csv') as csvfile:
    data = csv.DictReader(csvfile)
sampled_data = random.sample(list(data), 20)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading