我有一个看起来像这样的数据帧:foo = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [6,7,8]})foo列中的list_of_columns = ['a','b']列列表.

list_of_columns由用户动态 Select ,因此可以是['a','b'],也可以是['a','c']['c']['a','b','c']

我希望list_of_columns中的每column个创建(嵌套)for个循环,并以以下方式查询数据帧:

在 case list_of_columns = ['a','b']中,循环如下:

for a in foo.a.unique():
    for b in foo.b.unique():
        print(foo.query(f'a=={a} and b=={b}'))

在 case list_of_columns = ['a']中,循环如下:

for a in foo.a.unique():
    print(foo.query(f'a=={a}'))

在 case list_of_columns = ['a','b','c']中,循环如下:

for a in foo.a.unique():
    for b in foo.b.unique():
        for c in foo.c.unique():
            print(foo.query(f'a=={a} and b=={b} and c=={c}'))

有没有办法用python编程实现这一点?

推荐答案

从本质上讲,看起来你想在独特的组合上循环?

但是,当您随后查询有效的数据帧时,您会获得许多空数据帧.

for _,g in foo.groupby(list_of_columns):
    print('---')
    print(g)

输出:

---
   a  b  c
0  1  4  6
---
   a  b  c
1  2  5  7
---
   a  b  c
2  3  6  8

相比之下,嵌套循环的输出:

---
   a  b  c
0  1  4  6
---
Empty DataFrame
Columns: [a, b, c]
Index: []
---
Empty DataFrame
Columns: [a, b, c]
Index: []
---
Empty DataFrame
Columns: [a, b, c]
Index: []
---
   a  b  c
1  2  5  7
---
Empty DataFrame
Columns: [a, b, c]
Index: []
---
Empty DataFrame
Columns: [a, b, c]
Index: []
---
Empty DataFrame
Columns: [a, b, c]
Index: []
---
   a  b  c
2  3  6  8

Python相关问答推荐

这些变量是否相等,因为它们引用相同的实例,尽管它们看起来应该具有不同的值?

Python-Polars:如何用两个值的平均值填充NA?

Django序列化器没有验证或保存数据

Pandas read_jsonfuture 警告:解析字符串时,to_datetime与单位的行为已被反对

如果AST请求默认受csref保护,那么在Django中使用@ system_decorator(csref_protect)的目的是什么?

从管道将Python应用程序部署到Azure Web应用程序,不包括需求包

在应用循环中间保存pandas DataFrame

如何使用Google Gemini API为单个提示生成多个响应?

我必须将Sigmoid函数与r2值的两种类型的数据集(每种6个数据集)进行匹配,然后绘制匹配函数的求导.我会犯错

Select 用a和i标签包裹的复选框?

根据条件将新值添加到下面的行或下面新创建的行中

优化pytorch函数以消除for循环

如何使用数组的最小条目拆分数组

Telethon加入私有频道

django禁止直接分配到多对多集合的前端.使用user.set()

计算分布的标准差

合并帧,但不按合并键排序

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

在Admin中显示从ManyToMany通过模型的筛选结果

pysnmp—lextudio使用next()和getCmd()生成器导致TypeError:tuple对象不是迭代器''