基于嵌套的For循环创建列表

时间:2017-03-30 15:57:00

标签: python python-2.7 numpy

假设我使用的客户端计算机不允许使用pip或pandas,并且必须使用Python 2.7。不允许使用二进制文件并转换为exe文件。我正在阅读一个CSV,其中列标题为numpy的名称。

在我的数据集中,我正在尝试生成适用于Facility,Destination,Program#和其他因素的唯一组合的订单列表,其中p是读取的csv数据集。

CSV starting out

What it would look like if I did this in Excel. Order字段中的值是我想要的名为my_orders变量的列表。

我目前的代码如下:

progs = np.unique(p['Program'])
facil = np.unique(p['Facility'])
dest = np.unique(p['Destination']) 
reqs = np.unique(p['Requested'])
prods = np.unique(p['Produced'])
tier1 = np.unique(p['Tier1'])
tier2 = np.unique(p['Tier2'])

接下来是最初用pandas和Python3编写的以下方法,直到发现只有2.7和numpy可用:

for a in range(len(progs)):
    print("on Program ",a)
    ProgChild = {"name":progs[a], 'children':[]}
    for r in range(len(reqs)):
        reqChild = {"name":reqs[r], 'children':[]}
        for s in range(len(prods)):
            prodChild = {'name':prods[s], "children":[]}
            for g in range(len(progs)):
                programChild = {'name':progs[g], "children":[]}
                for i in range(len(facil)):
                    FacilChild={"name":facil[i], "children":[]}
                    for c in range(len(tier1)):
                        Tier1Child={"name":tier1[c], "children":[]}
                        for d in range(len(tier2)):
                            # here's where I'm in trouble:
                            Order_Cond = np.array[[progs[a]& reqs[r]&
                                prods[s]&progs[g]& facil[i]& tier1[c]]
                            my_orders = np.where(p['Orders'], Order_cond)
                            print my_orders
                            # do other things

正如您所看到的,最初的意图是使用For循环来设置一个例程,该例程只返回来自设施,目标,程序等的唯一组合的Orders列表.Direct_cond变量显然具有错误的语法。

如果这是在SQL中我只是说“从My_Data中选择订单,其中progs = a& reqs = r;”等等。

我还考虑了列表理解,但它也不起作用:

list(x for p['Orders'] in p if p['Orders'] in Order_cond)

同样,目标是创建一个订单列表并存储在my_orders中,然后我将其用于其他功能。

2 个答案:

答案 0 :(得分:0)

我没有关注你的整个嵌套代码,但这是一种识别符合特定条件的结构化数组中记录的方法

制作一个包含3个字段的示例数组:

In [447]: dt = np.dtype('S10,S10,int')
In [448]: data = np.ones((10,),dt)
In [451]: data['f0']='one two three four five six seven eight nine ten'.split()
In [452]: data['f1']='a b c a b c a b c a'.split()
In [453]: data['f2']=np.arange(10)
In [454]: data
Out[454]: 
array([(b'one', b'a', 0), (b'two', b'b', 1), (b'three', b'c', 2),
       (b'four', b'a', 3), (b'five', b'b', 4), (b'six', b'c', 5),
       (b'seven', b'a', 6), (b'eight', b'b', 7), (b'nine', b'c', 8),
       (b'ten', b'a', 9)], 
      dtype=[('f0', 'S10'), ('f1', 'S10'), ('f2', '<i4')])

测试一个字段:

In [461]: cond = data['f0']==b'three'
In [462]: cond
Out[462]: array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)

另一个有几个匹配的字段:

In [463]: cond = data['f1']==b'c'
In [464]: cond
Out[464]: array([False, False,  True, False, False,  True, False, False,  True, False], dtype=bool)

结合多个现场测试:

In [465]: cond = (data['f1']==b'c') & (data['f0']==b'three') & (data['f2']==2)
In [466]: cond
Out[466]: array([False, False,  True, False, False, False, False, False, False, False], dtype=bool)
In [467]: data[cond]
Out[467]: 
array([(b'three', b'c', 2)], 
      dtype=[('f0', 'S10'), ('f1', 'S10'), ('f2', '<i4')])

或者去sql路线:

In [468]: import sqlite3
In [469]: conn=sqlite3.connect(':memory:')
In [470]: cur = conn.cursor()
In [471]: cur.execute('''CREATE TABLE array (f0 str, f1 str, f2 int)''')
Out[471]: <sqlite3.Cursor at 0xaa0a38a0>
In [472]: cur.executemany("INSERT INTO array VALUES (?,?,?)",data)

data的元素看起来就像一个元组;所以插入是微不足道的。

Out[472]: <sqlite3.Cursor at 0xaa0a38a0>
In [473]: cur.execute('select * from array')
Out[473]: <sqlite3.Cursor at 0xaa0a38a0>
In [474]: cur.fetchall()
Out[474]: 
[(b'one', b'a', b'\x00\x00\x00\x00'),
 (b'two', b'b', b'\x01\x00\x00\x00'),
 (b'three', b'c', b'\x02\x00\x00\x00'),
 ...
 (b'ten', b'a', b'\t\x00\x00\x00')]
In [486]: cur.execute('select * from array where f0==(?)',(b"four",))
Out[486]: <sqlite3.Cursor at 0xaa0a38a0>
In [487]: cur.fetchall()
    Out[487]: [(b'four', b'a', b'\x03\x00\x00\x00')]
In [488]: cur.execute('select * from array where f0==(?) or f1==(?)',(b"four",b"c"))
Out[488]: <sqlite3.Cursor at 0xaa0a38a0>
In [489]: cur.fetchall()
Out[489]: 
[(b'three', b'c', b'\x02\x00\x00\x00'),
 (b'four', b'a', b'\x03\x00\x00\x00'),
 (b'six', b'c', b'\x05\x00\x00\x00'),
 (b'nine', b'c', b'\x08\x00\x00\x00')]

这个例子需要更清晰,但它可以大致了解可能的情况。

答案 1 :(得分:0)

所以你想从csv文件中选择与某些列的某些值相对应的行?在python 2.7中没有少?好吧,这对2.7

并不困难

使用csv.DictReader可以找到最简单的方法,它会将csv文件作为字典行读入,其中的键对应于每行的列标签。然后,给定一个您想要选择的键和值对的字典,下面的代码返回一个符合您想要的字典数组。如果您想删除键值配对并且只有值数组this is trivially implemented。由于您可以将csv文件转换为字典列表,因此selecting a dictionary from an array with certain values for keys

import csv

def dict_has_key_values(dict, dict_key_values):
    for key in dict_key_values:
        if not(key in dict and dict[key] == dict_key_values[key]):
           return False
    return True

def select_from_dict(csv_dict_reader, dict_key_values):
    list_of_dict = []
    for row_dict in csv_dict_reader:
        if dict_has_key_values(dict, dict_key_values):
             list_of_dict.append(dict)
    return list_of_dict


with open('yourfile.csv') as csvfile:
    selected_key_values = {...}
    reader = csv.DictReader(csvfile)
    selected_rows = select_from_dict(reader, selected_key_values)

selected_rows现在应该包含每一行

答:至少在selected_key_values中有每个键,

B:与这些键相关的值是相同的。