gpt4 book ai didi

python - pandas.DataFrame.apply() 使用索引作为参数

转载 作者:行者123 更新时间:2023-12-01 04:11:52 37 4
gpt4 key购买 nike

我正在尝试将函数应用于 pandas 数据框中的每一行。列数是可变的,但我也在函数中使用索引

def pretend(np_array, index):
sum(np_array)*index

df = pd.DataFrame(np.arange(16).reshape(8,2))
answer = df.apply(pretend, axis=1, args=(df.index))

我将其形状调整为 8x2,但我希望它能够适用于我传递的任何形状。

最佳答案

索引值可以通过.name属性访问:

In [3]:
df = pd.DataFrame(data = np.random.randn(5,3), columns=list('abc'))
df

Out[3]:
a b c
0 -1.662047 0.794483 0.672300
1 -0.812412 -0.325160 -0.026990
2 -0.334991 0.412977 -2.016004
3 -1.337757 -1.328030 -1.005114
4 0.699106 -1.527408 -1.288385

In [8]:
def pretend(np_array):
return (np_array.sum())*np_array.name
df.apply(lambda x: pretend(x), axis=1)

Out[8]:
0 -0.000000
1 -1.164561
2 -3.876037
3 -11.012701
4 -8.466748
dtype: float64

您可以看到第一行变为0,因为索引值为0

关于python - pandas.DataFrame.apply() 使用索引作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34817416/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com