use*_*495 1 python recursion loops pandas
我写了一个简单的递归函数来删除具有最大总和的列,直到数据帧减少到我想要的大小.这是代码:
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)
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,首先删除列'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
Run Code Online (Sandbox Code Playgroud)
尽量避免使用全局变量 - 在递归中使用它!在函数中添加一个额外的参数.这将需要是一个列表来存储已删除的列名,但我们将默认值设置为,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)
Run Code Online (Sandbox Code Playgroud)
版画
['e', 'd', 'c']
Run Code Online (Sandbox Code Playgroud)