【问题标题】:create dataframe by randomly sampling from multiple files通过从多个文件中随机抽样来创建数据框
【发布时间】:2018-08-20 16:46:33
【问题描述】:

我有一个文件夹,里面有几个 2000 万个记录制表符分隔的文件。我想创建一个熊猫数据框,我从每个文件中随机抽取 2 万条记录,然后将它们一起附加到数据框中。有人知道怎么做吗?

【问题讨论】:

    标签: python-2.7 pandas


    【解决方案1】:

    您可以读取特定文件夹中的所有文本文件。然后你可以使用 pandas Dataframe.sample (link to docs)。

    我提供了一个完全可重现的示例,其中包含两个使用 200 行创建的示例 .txt 文件。然后,我随机抽取 10 行样本,并将样本附加到最终数据帧中。

    import pandas as pd
    import numpy as np
    import glob
    
    # Change the path for the directory
    directory = r'C:\some\example\folder'
    # I create two test .txt files for demonstration purposes with 200 rows each
    df_test = pd.DataFrame(np.random.randn(200, 2), columns=list('AB'))
    df_test.to_csv(directory + r'\test_1.txt', sep='\t', index=False)
    df_test.to_csv(directory + r'\test_2.txt', sep='\t', index=False)
    
    df = pd.DataFrame()
    
    for filename in glob.glob(directory + r'\*.txt'):
        df_full = pd.read_csv(filename, sep='\t')
        df_sample = df_full.sample(n=10)
        df = df.append(df_sample)
    

    【讨论】:

      猜你喜欢
      • 2021-04-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多