简体   繁体   English

在python中获取没有numpy或pandas的数组的样本

[英]Take a sample of an array without numpy or pandas in python

I am trying to create a "pythonic" way of taking a small subset of a very large array in python. 我正在尝试创建一种“ pythonic”的方式来获取python中很大数组的一小部分。

I am currently taking in a csv with 58 columns and 4960 rows with the following codes: 我目前正在使用具有以下代码的58列和4960行的csv:

def import_normal_csv(file):
    # Create blank array
    results = []
    # Open file
    with open(file) as csvfile:
        # read in file changing values to floats
        reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
        for row in reader:
            results.append(row)
    return results

def main():
    print(" Working SPAM Dataset... ")
    # Create a raw data array without numpy
    spam_raw_data = import_normal_csv('spam.csv')

    # CREATE SUBSET OF SPAM_RAW_DATA HERE

    random.shuffle(spam_raw_data)

I have seen various ways to do this using numpy or pandas , but I would like to do this naturally without those libraries. 我已经看到了使用numpypandas进行此操作的各种方法,但是我很想在没有这些库的情况下自然地进行操作。 Instead of my massive array, how could I instead take in only...500 rows (or some arbitrary number significantly less than nearly 5000)? 而不是我的大量数组,我怎么能只接收... 500行(或一些明显少于5000的任意行)?

You can use the builtin random library, for example: 您可以使用内置的random库,例如:

import random

random.sample(data, 500)

This will give you a list of 500 list s, each representing one row. 这会给你一个list的500个list S,各自代表一行。

Use random.sample : 使用random.sample

subset_size = 500
random.sample(spam_raw_data, subset_size)

Also note your import_normal_csv function can be simplified: 还要注意,您的import_normal_csv函数可以简化:

def import_normal_csv(file):
    with open(file) as csvfile:
        reader = csv.reader(csvfile, quoting=csv.QUOTE_NONNUMERIC)
        return list(reader)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM