首页 > 解决方案 > 根据列表过滤数据框列

问题描述

我有一个数字列表,我想找到这些数字的所有不同组合而不重复。从那里,下一步是按列号过滤数据帧 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#

运行此代码,我得到以下错误:cannot do slice indexing on with these indexer [[1]] of class 'list'

我认为我的代码中的els也是列表(和 temp_list)的列表。所以我尝试将它们展平以获得一个列表(例如,这里已经介绍了这个主题:Making a flat list out of list of lists in Python

但是,在运行此行时

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

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

标签: pandaslistitertools

解决方案


使用示例数据框:

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 

推荐阅读