[英]How to flat nested dict keys and values into flat lists of their types and variables?
[英]dict comprehension for nested lists to filter values of multiple variables
我在遍歷的列表上有一個dict理解的工作示例:這會生成各種指示符(選擇),將我的數據行分成案例(順便說一句,這不是排他的)。
對於上下文:當我將表聚合到某些組時,這樣做是為了統計特定行(由列定義的標准)的情況。 這些指標現在被收集在單獨的數據框中,以便分別導出,盡管我也很高興將所有數據保存在一個數據框中,以便在可能的情況下進行一次匯總,連接和導出。
現在,我想將其嵌套到另一個循環中。 該循環將定義我為值選擇/過濾的其他變量。 因此,項目0仍將是條件本身(指標的總和為案例數),但項目1為TKOST
的選定案例( TKOST
將看到用於單獨標准的選擇性總和),項目2為另一個變量現在讀。
但是對於該循環來說,也要影響變量名是有意義的,例如,對於計數(或neuro_count
)具有空白的neuro
變量,對於神經病例而言,對於neuro_cost
的總和具有TKOST
等。這怎么可能?
示例代碼基本上來自Alexander在另一個問題上的答案 。 提供文件I / O和pandas
部分用於上下文。
import pandas as pd
items = {'neuro': 'N',
'cardio': 'C',
'cancer': 'L',
'anesthetics': 'N01',
'analgesics': 'N02',
'antiepileptics': 'N03',
'anti-parkinson drugs': 'N04',
'psycholeptics': 'N05',
'psychoanaleptics': 'N06',
'addiction_and_other_neuro': 'N07',
'Adrugs': 'A',
'Mdrugs': 'M',
'Vdrugs': 'V',
'all_drugs': ''}
# Create data containers using dictionary comprehension.
dfs = {item: pd.DataFrame() for item in items.keys()}
monthly_summaries = {item: list() for item in items.keys()}
# 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/STUB_' + str(year) + '_mon'+ str(month) +'.txt'
monthly = pd.read_table(filename,usecols=[0,3,32])
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()]
# 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()}
# Now regroup the aggregate monthly summaries.
monthly_summaries = {name: dfs[name].reset_index().groupby(['LopNr','year','month']).sum()
for name in items.keys()}
# Finally, save the aggregated results to files.
[monthly_summaries[name].to_csv('PATH/monthly_{0}_costs.csv'.format(name))
for name in items()]
您應該首選顯式的for循環:
for name in items.keys():
monthly_summaries[name].append(dfs[name].groupby(['LopNr','year','month']).sum()
.astype(int, copy=False)
# rather than
[monthly_summaries[name].append(dfs[name].groupby(['LopNr','year','month']).sum()
.astype(int, copy=False))
for name in items.keys()]
后者創建了一個None
的偽列表(並且可讀性較差),因此效率較低。
前者可以讓您輕松築巢...
但是對於這個循環來說,也影響變量名是有意義的,例如,對於計數(或Neuro_count)具有空白的神經變量,對於神經病例,對於TKOST的總和具有Neuro_cost等。這怎么可能?
我通常會添加列來進行這些計數,這樣就可以將其矢量化/拆分/其他。
(然后不要將這些列寫到csv中。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.