Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在未知参数数上选择行_Python_Pandas_Indexing_Itertools - Fatal编程技术网

Python在未知参数数上选择行

Python在未知参数数上选择行,python,pandas,indexing,itertools,Python,Pandas,Indexing,Itertools,我有一个例子,我可以简化为以下情况,在这种情况下,我引入一个数据帧,在循环中进行选择,并生成一个新的数据帧,其中包含满足条件的旧数据帧的子集: import pandas as pd import intertools g = ['M', 'M', 'F', 'F'] a = [20, 33, 20, 50] Zip = [21202, 21018, 21202, 22222] d = [0, -3, 8] parameters = (g, a) names = ['gender', 'ag

我有一个例子,我可以简化为以下情况,在这种情况下,我引入一个数据帧,在循环中进行选择,并生成一个新的数据帧,其中包含满足条件的旧数据帧的子集:

import pandas as pd
import intertools
g = ['M', 'M', 'F', 'F']
a = [20, 33, 20, 50]
Zip = [21202, 21018, 21202, 22222] 
d = [0, -3, 8]

parameters = (g, a)
names = ['gender', 'age']

df = pd.DataFrame({'age':a, 'gender':g, 'd':d, 'Zip':Zip})

for values in itertools.product(*parameters):
    thesevalues = ((df[names[0]] == values[0]) & (df[names[1]] == values[1]]))
    subdf = df[thesevalues]
很好,但是如果我还想在参数中包含邮政编码和名称呢。我还必须在“thesevalues”中手动引入第三个选择标准。我可能忽略了使该标准中的参数列表与参数列表相适应的功能?循环似乎不是一个好选择。。。还有别的办法吗?谢谢

IIUC您需要:


您的代码没有真正意义,因为您将通过迭代所有组合来子集…所有数据帧…您的代码不起作用。是的,代码起作用,这只是一个小示例,实际上,将使用一个参数组合选择许多行,然后我需要添加一个不属于选择的列。
parameters = (g, a, Zip)
names = ['gender', 'age', 'Zip']

df = pd.DataFrame({'age':a, 'gender':g, 'd':d, 'Zip':Zip})
print (df)

for values in product(*parameters):
    #http://stackoverflow.com/a/20528566/2901002
    thesevalues = np.logical_and.reduce([df[names[x]] == values[x] for x in range(len(parameters))])
    subdf = df[thesevalues]
    print (subdf)