内存效率高的Python(pandas)从每个时段一个csv文件聚合类别

2024-06-09 21:56:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力避免pandas或IOPro(仍在调查)的分割错误,因此我正在寻找其他解决方案,特别是更有效的解决方案。下面的代码在小数据情况下运行良好,但是在Linux服务器上,使用256GB RAM、版本为pandas 0.16.2np19py26_0、iopro 1.7.1np19py27_p0和python 2.7.10 0的Linux服务器上,每个月读取的数据量很少,但会崩溃。

我在这里所做的是汇总每个人(LopNr)和每个月的药品购买记录(成本以TKOST为单位),同时使用ATC代码将药品分类。

因此,虽然原始数据看起来像这样,但在每月的csv文件中(比如说2006年7月,csv中的许多其他列我不需要):

LopNr TKOST ATC
1         5 N01
1        11 N01
1         6 N15

等等

我要的是聚合面板

^{pr2}$

可以单独用于几个类别(例如,对于ATCs,neuro在这里以N开头),也可以在单个数据文件中为这些类别提供单独的摘要(因此使用neuro列等)。

我选择了IOPro和not simple pandas来提高内存效率,但是现在我遇到了一个分割错误。

^{3}$

Tags: csv代码服务器pandaslinux错误解决方案类别
1条回答
网友
1楼 · 发布于 2024-06-09 21:56:14

您的代码相当重复,可以通过字典和列表理解来简化。这个解决方案应该可以消除你的内存问题,因为你一次只处理一个月的数据(尽管你的每月摘要列表越来越多,我不相信会占用太多内存)。在

但我不能用上面的代码来测试。在

import pandas as pd
import iopro

items = {'neuro': 'N', 
         'cardio': 'C', 
         'cancer': 'L', 
         'addiction': 'N07', 
         'Adrugs': 'A', 
         'Mdrugs': 'M', 
         'Vdrugs': 'V', 
         'all_drugs': ''}

# 1. Create data container using dictionary comprehension.
monthly_summaries = {item: list() for item in items.keys()}

# 2. Perform monthly groupby operations.
for year in xrange(2005, 2013):
    for month in xrange(1, 13):
        if year == 2005 and month < 7:
            continue
        filename = 'PATH/lmed_' + str(year) + '_mon'+ str(month) +'.txt'
        adapter = iopro.text_adapter(filename,
                                     parser='csv', 
                                     field_names=True, 
                                     output='data frame', 
                                     delimiter='\t')
        monthly = adapter[['LopNr','ATC','TKOST']][:]
        monthly['year'] = year
        monthly['month'] = month
        dfs = {name: monthly[(monthly.ATC.str.startswith('{0}'.format(code))) 
                             & (~(monthly.TKOST.isnull()))]
                     for name, code in items.iteritems()}
        [monthly_summaries[name].append(dfs[name].groupby(['LopNr','year','month']).sum()
                                        .astype(int, copy=False)) 
         for name in items.keys()]

# 3. Now concatenate all of the monthly summaries into separate DataFrames.
dfs = {name: pd.concat([monthly_summaries[name], ignore_axis=True]) 
       for name in items.keys()}

# 4. Now regroup the aggregate monthly summaries.
monthly_summaries = {name: dfs[name].reset_index().groupby(['LopNr','year','month']).sum()
                    for name in items.keys()}

# 5. Finally, save the aggregated results to files.
[monthly_summaries[name].to_csv('PATH/monthly_{0}_costs.csv'.format(name))
 for name in items()]

相关问题 更多 >