Creating a representative sample from a large CSV

2019-08-10 15:24发布

问题:

I have the following dataset:

head -2 trip_data_1.csv

medallion,hack_license,vendor_id,rate_code,store_and_fwd_flag,pickup_datetime,dropoff_datetime,passenger_count,trip_time_in_secs,trip_distance,pickup_longitude,pickup_latitude,dropoff_longitude,dropoff_latitude
89D227B655E5C82AECF13C3F540D4CF4,BA96DE419E711691B9445D6A6307C170,CMT,1,N,2013-01-01 15:11:48,2013-01-01 15:18:10,4,382,1.00,-73.978165,40.757977,-73.989838,40.751171

A simple count of records by date gives me the following output:

Count  Date
557203 2013-01-26
543734 2013-01-18
537188 2013-01-25
533039 2013-01-24
531161 2013-01-31
521398 2013-01-11
520520 2013-01-23
512533 2013-01-17
510530 2013-01-19
507429 2013-01-12
500065 2013-01-16
496899 2013-01-15
496005 2013-01-22
487949 2013-01-10
482378 2013-01-30
478437 2013-01-04
477380 2013-01-29
473804 2013-01-05
470833 2013-01-27
459393 2013-01-20
457471 2013-01-09
450789 2013-01-28
443650 2013-01-14
442541 2013-01-13
441778 2013-01-08
441233 2013-01-03
412630 2013-01-01
407363 2013-01-07
403667 2013-01-06
393001 2013-01-02
384614 2013-01-21

My question is: How do I create a subset (preferably 10% of total rows) such that it is representative of the entire dataset? I need to ensure that I have at least 40,000 rows of data for each date.

Link to the dataset

回答1:

You can use awk like this:

awk 'rand()>0.9' trip_data_1.csv

It just generates a random number between 0 and 1 as it reads each record, and if that random number is > 0.9, it prints the record - thus it should print 10% of your records on average.

If you want the header as well, use:

awk 'FNR==1 || rand()>0.9' trip_data_1.cv

If you want it truly random, rather than predictably random :-)

awk 'BEGIN{srand()} FNR==1 || rand()>0.9' trip_data_1.cv


回答2:

Get a random sample:

sort -R filename | head -n $(($(wc -l filename | awk '{print $1}') / 10))
# random sort    | get     10%   ( length divided by 10 )

You have to remove the CSV header first, and then attach it back. Left it as an exercise :)

For efficiency reasons, you might want to implement this with a native app.