【问题标题】:Large scale pivot table in PythonPython中的大规模数据透视表
【发布时间】:2017-05-23 06:15:42
【问题描述】:

我有 100-300Go 的 csv 格式(数字 + unicode 文本)数据,需要对此进行常规数据透视表作业。在谷歌搜索/StackOverflow-ing 之后,找不到满意的答案(仅部分)。 想知道哪种解决方案对于单机(64Go RAM)最快:

1) 转换并插入 PostGres 并通过 SQL 在 PostGres DB 中处理所有内容? (或 MySQL....)

2) 在 Pandas 中分块加载 csv 并手动一一处理?

3) 加载 csv + 转换为 HDF 并按块处理 HDF ?

4) 其他解决方案。

【问题讨论】:

    标签: pandas pivot-table bigdata


    【解决方案1】:

    对于在单台机器上工作,PostgreSQL 可能是您列出的 3 个选项中的最佳选择。

    为了控制内存使用,您可以使用partitioning 并按块处理数据。

    【讨论】:

    • 对Pivot表有什么真实体验吗?
    • 是的,我以前使用这 3 个工具来构建数据透视表和 olap 多维数据集。在几个 100 Gb 的范围内,postgreSQL 运行良好,只要一个分区数据以便它可以在内存中工作并避免使用 SWAP。
    • 如果您的数据透视表有 2000 列怎么办?您如何使用关系数据库进行数据透视,因为其中许多列的限制是 1024 列
    • 你应该在一个新问题@user798719上发布它
    【解决方案2】:

    提问者一定已经解决了问题,对于可能遇到这个问题的其他人,我的回答可能会有所帮助。 试试这个解决方案(根据你的数据集转换它),我在 50-80 GB 上尝试过,添加 numpy 会提高性能。

    import pandas as pd
    from datetime import date
    from datetime import datetime 
    
    print("1 Load rec =", datetime.now())
    df6 = pd.read_csv('sampleDataframeFlux/sampleDataframeFlux.csv',low_memory=False, memory_map=True,engine='c',na_filter=False,index_col=False,usecols=["time", "Label","Server","value"])
    print("shape",df6.shape)
       
    print("2 Create dataframe =",datetime.now())
    df6["Label"]=df6["Server"]+"|"+df6["Label"]
    df6.drop(['Server'],axis=1,inplace=True)
        
    print("3 Time trim =", datetime.now())
    df6['time']=df6['time']//1000000000
    print("shape",df6.shape)
      
    print("4 Round Epoch to nearest multiple of 5 =", datetime.now())
    df6['time']=5*round(df6['time']/5)
    print("shape",df6.shape)
      
    print("5 Pivot dataframe=", datetime.now())
    df6=df6.pivot_table(index='time', columns=["Label"],values="value",fill_value=0)
    print("shape",df6.shape)
    
    print("6 Epoch to UTC =", datetime.now())
    df6.index=pd.to_datetime(df6.index, unit='s')
        
    print("7 Convert to type category to reduce memory =", datetime.now())
    df6=df6.astype('category')
    print("shape",df6.shape)
       
    print("8 Start to write to a file  =", datetime.now())
    df6.to_csv('file_11.csv', header=True, chunksize=500000)
    print("9 Finish =", datetime.now())
    

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多