使用带有 iloc pandas 的函数应用

apply using a function with iloc pandas

我有一个包含 40 列的数据集,我想定义一个操作这些列的函数。

例如,

p = {'val1': [10, 20, 30, 40],
    'val2': [15, 25, 35, 45]}

data = pd.DataFrame(p, columns=['val1', 'val2'])
data

我有这个数据,我做了下面的操作

inc = 100*((data.iloc[:, -1]/ data.iloc[:, -1-1])-1)
inc

结果是

0    50.000000
1    25.000000
2    16.666667
3    12.500000
dtype: float64

我想要select最大值和最大值的索引,我做了以下操作

(inc.idxmax(), max(inc))

我得到了以下结果

(0, 50.0)

现在,我定义一个函数

def increase(column):
    inc = 100*((data.iloc[:, -column]/ data.iloc[:, -column-1])-1)
    return (inc.idxmax(), max(inc))

我 select 列向后。

并且我想将此功能应用于我的所有专栏

new_data = data.apply(increase)

当我使用它时出现错误

IndexError: positional indexers are out-of-bounds

如果我使用 applymap,我会得到同样的错误

我能做什么?

如果我没理解错的话,你想在函数中使用多列。 apply 不是这里的解决方案,因为它当时在一行或一列(轴=0 或 1)上工作。

所以我的建议是这样每次迭代输入 2 列:

def increase(col1,col2):
   inc = 100*((col2/ col1)-1)
   return (inc.idxmax(), max(inc))

lst = []
for i in range(len(data.columns)):
    j=i+1
    if j<len(data.columns):
        col1 = data[data.columns[i]]
        col2 = data[data.columns[j]]
        lst.append(increase(col1,col2))

pd.DataFrame(lst)