根据列表过滤数据框列

CTXR

我有一个数字列表,我想不重复地找到这些数字的所有不同组合。从那里,下一步是按列号过滤数据帧 df 的列;列号是先前找到的组合。然后我必须在每次迭代时对新的过滤数据帧运行一些计算。

假设我有以下代码:

import pandas as pd 
import numpy as np
import itertools

lst = [1, 2, 3] #intial list
    for i in range(1,4) #combs can have 1, 2 or 3 numbers  
        combs = [] #empty list to store combinations
        els = [list(x) for x in itertools.combinations(lst, i)]
        for j in range(0,len(els)): #loop through each combination found
                temp_list=els[j]
                temp_df=df.iloc[:temp_list]

                #...Do some calculations with temp_df#

运行此代码,我收到以下错误:无法使用类“列表”的这些索引器 [[1]] 进行切片索引

我认为我的代码中的els也是一个列表(和 temp_list)列表。因此,我尝试将它们展平以获得列表(此主题已在此处涵盖,例如:从 Python 中的列表列表制作平面列表

但是,在运行此行时

flat_list = [item for sublist in temp_list for item in sublist]

我收到一个新错误:“int”对象不可迭代。如何获取可用于过滤数据框的数字列表?谢谢

拉尔夫23

使用示例数据框:

df = pd.DataFrame([[0, 1, 2], [3, 4, 5], [6, 7, 8]], columns=[1, 2, 3])

给予:

   1  2  3
0  0  1  2
1  3  4  5
2  6  7  8

以下代码应该可以实现您想要的。请注意,我在.loc这里使用,而不是.iloc,因为我指定的是列而不是索引如果要指定索引,请使用.iloc.

import itertools

#Initial list
lst = [1, 2, 3]

#Assemble all combinations
combs = [list(x) for i in range(1,4) for x in itertools.combinations(lst, i)]

#Use .loc
for comb in combs: #For each combination
    temp_df = df.loc[:,comb]
    print(temp_df)

产量:

   1
0  0
1  3
2  6 

   2
0  1
1  4
2  7 

   3
0  2
1  5
2  8 

   1  2
0  0  1
1  3  4
2  6  7 

   1  3
0  0  2
1  3  5
2  6  8 

   2  3
0  1  2
1  4  5
2  7  8 

   1  2  3
0  0  1  2
1  3  4  5
2  6  7  8 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章