【问题标题】:pandas HDF select does not recognise column name熊猫 HDF 选择不识别列名
【发布时间】:2015-03-24 02:23:52
【问题描述】:

我正在尝试在只有 4gb 内存的机器上处理一个大 (2gb) csv 文件(不要问),以生成一个不同的、格式化的 csv,其中包含需要一些处理的数据子集。我正在读取文件并创建一个 HDFstore,稍后我会查询输出所需的数据。一切正常,除了我无法使用 Term 从商店中检索数据 - 错误消息返回 PLOT 不是列名。个别变量看起来很好,商店是我所期望的,我只是看不到错误在哪里。 (nb pandas v14 和 numpy1.9.0)。对此非常新,因此为笨拙的代码道歉。

#wibble wobble -*- coding: utf-8 -*-
# short version
def filesport():
    import pandas as pd
    import numpy as np
    from pandas.io.pytables import Term

    Location = r"CL_short.csv"
    store = pd.HDFStore('blarg.h5')

    maxlines = sum(1 for line in open (Location))
    print maxlines
 #set chunk small for test file   
    chunky=4
    plotty =pd.DataFrame(columns=['PLOT'])
    dfdum=pd.DataFrame(columns=['PLOT', 'mDate', 'D100'])

#read file in chunks to avoid RAM blowing up    
    bucket = pd.read_csv(Location, iterator=True, chunksize=chunky, usecols=   ['PLOT','mDate','D100'])

    for chunk in bucket:
        store.append('wibble', chunk, format='table', data_columns=['PLOT','mDate','D100'], ignore_index=True)

#retrieve plot numbers and select unique items
    plotty = store.select('wibble', "columns = ['PLOT']")
    plotty.drop_duplicates(inplace=True)

#iterate through unique plots to retrieve data and put in dataframe for output
    for index, row in plotty.iterrows():
        dfdum = store.select('wibble', [Term('PLOT', '=', plotty.iloc[index]['PLOT'])])
#process dfdum for output to new csv

    print("successful completion")
filesport()

【问题讨论】:

  • 我会回答我自己的问题,以防其他人遇到问题并发现自己处于网络这个黑暗、孤独的角落。问题是 Term 需要是一个字符串,而 Term 的数字部分是一个数字变量而不是字符串。我无法让 str 函数在 Term() 部分中工作,但这确实适用于 index, row in plotty.iterrows(): condition = 'PLOT =' + str(plotty.iloc[index]['PLOT'] ) dfdum = store.select('wibble', [Term(condition)]).
  • 对于索引,plotty.iterrows() 中的行:条件 = 'PLOT =' + str(plotty.iloc[index]['PLOT']) dfdum = store.select('wibble', [期限(条件)])

标签: python csv pandas hdfstore


【解决方案1】:

最终列表为那些希望通过风滚草战斗到达这里并且同样对处理大型 .csv 文件和尝试检索/处理数据的各种方法感到困惑的人。最大的问题是正确使用 pytables 术语的语法。尽管有几个例子表明可以使用“A > 20”等,但这对我来说从来没有用过。我设置了一个包含 Term 查询的字符串条件,这很有效(它在文档 TBF 中)。
还发现更容易查询 HDF 以直接从列表中的商店检索唯一项目,然后可以对列表进行排序和迭代以逐个地检索数据。请注意,我希望最终的 csv 文件具有绘图,然后是所有 D100 数据按日期顺序排列,因此最后是枢轴。
分块读取 csv 文件意味着从商店检索到的每个图都有一个标题,并且这被写入了最终的 csv,这把事情搞砸了。我确信有一种比我在这里展示的更优雅的方式只写一个标题。
它工作,大约需要 2 小时来处理数据并生成最终的 csv 文件(初始文件 2GB,30+百万行,100,000+ 独特图的数据,机器有 4GB 的 RAM,但运行 32 位,这意味着只有 2.5GB RAM 可用)。
祝你好运,如果你有类似的问题,我希望你觉得这很有用

#wibble wobble -*- coding: utf-8 -*-

def filesport():
    import pandas as pd
    import numpy as np
    from pandas.io.pytables import Term

    print (pd.__version__)
    print (np.__version__)

    Location = r"conliq_med.csv"
    store = pd.HDFStore('blarg.h5')

    maxlines = sum(1 for line in open (Location))
    print maxlines
    chunky=100000

#read file in chunks to avoid RAM blowing up select only needed columns
    bucket = pd.read_csv(Location, iterator=True, chunksize=chunky, usecols= ['PLOT','mDate','D100'])

    for chunk in bucket:
        store.append('wibble', chunk, format='table', data_columns=['PLOT','mDate','D100'], ignore_index=True)

#retrieve unique plots and sort 
    plotty = store.select_column('wibble', 'PLOT').unique()
    plotty.sort()
#set flag for writing file header
    i=0

#iterate through unique plots to retrieve data and put in dataframe for output
    for item in plotty:
        condition = 'PLOT =' + str(item)
        dfdum = store.select('wibble', [Term(condition)])
        dfdum["mDate"]= pd.to_datetime(dfdum["mDate"], dayfirst=True)
        dfdum.sort(columns=["PLOT", "mDate"], inplace=True)
        dfdum["mDate"] = dfdum["mDate"].map(lambda x: x.strftime("%Y - %m"))
        dfdum=dfdum.pivot("PLOT", "mDate", "D100")

#only print one header to file 
        if i ==0:
             dfdum.to_csv("CL_OP.csv", mode='a')  
             i=1
        else:
             dfdum.to_csv("CL_OP.csv", mode='a', header=False)

    print("successful completion")

filesport()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2019-07-13
    • 2023-03-19
    • 2013-02-03
    • 2021-12-21
    相关资源
    最近更新 更多