【问题标题】:Filtering and rearranging very large dictionary array without pandas在没有熊猫的情况下过滤和重新排列非常大的字典数组
【发布时间】:2017-08-21 19:16:51
【问题描述】:

我有一个非常大的字典数组,如下所示:

masterArray =[{'value': '-1', 'product': 'product1', 'Customer': 'customer1', 
'Sensor': 'sensor1', 'Date': '20170302', 'type': 'type1', 'ID': '100'}, 
{'value': '20', 'product': 'product1', 'Customer': 'customer1',  
'Sensor': 'sensor1','Date': '20170302', 'type': 'type2', 'ID': '100'},
{'value': '0', 'product': 'product1', 'Customer': 'customer1',  
'Sensor': 'sensor1', 'Date': '20170302', 'type': 'type1', 'ID': '101'}, 
{'value': '-5', 'product': 'product1', 'Customer': 'customer1',  
'Sensor': 'sensor1', 'Date': '20170302', 'type': 'type2', 'ID': '101'}]

我需要能够为每一天、产品、传感器和客户打印出单独的 csv,第一列作为 ID #s,类型作为其余列,值作为填充的数据行。

ID, type1, type2
100, -1, 20
101, 0, -5

我还创建了一个日期集和一个“组合”集来收集产品、传感器和客户的独特日期和组合。

不幸的是,我不被允许安装 pandas 库,尽管我认为我想做的就是这样做:

df = pd.DataFrame(masterArray)
df.head()
pivot = pd.pivot_table(df, index=['ID'], values=['value'], columns=['type'])


for date in dateset:
#filter for date
    pqd = pivot.query('Date == date')

for row in comboset:
    #filter for each output
    pqc = pqd.query('Customer == row[0] & product == row[1] & sensor == row[2]')

    outputName = str(row[0] + '_' + date + '_' + row[1] + '_' + row[2] + '.csv')
    filepath = os.path.join(path, outputName)
    pqc.to_csv(filepath) #print 

目前我的 pandas-less 想法是将我的 masterArray 更改为一个巨大的嵌套字典(我自己从其他输入 csv 文件创建 masterArray),但我不确定这是否是最有效的方法。我也不知道如何最好地为这么大的嵌套字典设置逻辑。请帮忙!

【问题讨论】:

    标签: python arrays dictionary nested


    【解决方案1】:

    你可以试试这样的:

    data_dict = {}
    for each in masterArray:
        if not data_dict.has_key(each['ID']):
            data_dict[each['ID']] = []
        data_dict[each['ID']].append({each['type']: each['value']})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-04
      • 1970-01-01
      • 2019-01-17
      • 2018-05-09
      • 1970-01-01
      • 2015-09-05
      • 2011-08-03
      相关资源
      最近更新 更多