我写了一个简单的递归函数来删除具有最大总和的列,直到数据帧减小到我想要的大小。这是代码:
s = pd.DataFrame({'a': [1,1,1,1,1,1],
'b': [2,2,2,2,2,2],
'c': [3,3,3,3,3,3],
'd': [4,4,4,4,4,4],
'e': [5,5,5,5,5,5]})
def recSelect(inputdf):
if inputdf.shape[1]<=2:
return inputdf
else:
total = inputdf.sum()
idx = total.idxmax()
inputdf.drop(idx, axis=1, inplace=True)
return recSelect(inputdf)
recSelect(s)
在上面的代码中,首先删除了“e”列,然后是“d”列,然后是“c”列。我的问题是:如何正确返回 'idx' 并获得 ['e', 'd', 'c'] 的列表??
这是我尝试过的方法,但它不起作用:
idxs = [] # create an empty list
def recSelect(inputdf):
if inputdf.shape[1]<=2:
return inputdf
else:
total = inputdf.sum()
idx = total.idxmax()
idxs.append(idx) # append each idx
inputdf.drop(idx, axis=1, inplace=True)
return recSelect(inputdf), idxs
请您参考如下方法:
尽量避免使用全局变量——在你的递归中使用它!向函数添加一个额外的参数。这需要是一个列表来存储删除的列名,但我们将默认值设置为 None,因此该列表不会在函数调用之间共享。在第一次调用时初始化空列表,并在每次删除列时更新它。
import pandas as pd
s = pd.DataFrame({'a': [1,1,1,1,1,1],
'b': [2,2,2,2,2,2],
'c': [3,3,3,3,3,3],
'd': [4,4,4,4,4,4],
'e': [5,5,5,5,5,5]})
def recSelect(inputdf, removed=None):
if not removed:
removed=[]
if inputdf.shape[1]<=2:
return inputdf, removed
else:
total = inputdf.sum()
idx = total.idxmax()
inputdf.drop(idx, axis=1, inplace=True)
removed.append(idx)
return recSelect(inputdf, removed)
vals, removed = recSelect(s)
print(removed)
打印
['e', 'd', 'c']
