gpt4 book ai didi

python Pandas : Using apply() to subtract a value from an array

转载 作者:太空狗 更新时间:2023-10-30 02:55:50 24 4
gpt4 key购买 nike

我想使用 pandas apply() 而不是遍历数据帧的每一行,据我所知这是更有效的过程。

我想做的很简单:

temp_arr = [0,1,2,3]
# I know this is not a dataframe, just want to show quickly how it looks like.
temp_df is a 4x4 dataframe, simply: [[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]
For each row in my temp_df, minus the corresponding number in the temp_arr.

因此,例如,我的数据框中的第一行是 [1,1,1,1],我想从它们中减去我的 temp_arr 中的第一项(即 0),因此输出应该是 [1, 1,1,1]。第二行是 [2,2,2,2],我想从中减去 temp_arr 中的第二项(即 1),所以输出也应该是 [1,1,1,1]。

如果我要减去一个常数,我知道我可以很容易地做到这一点:

temp_df.apply(lambda x: x-1)

但这里棘手的事情是我需要遍历我的 temp_arr 以获得减去的数字。有什么办法可以用 apply() 做到这一点吗?

最佳答案

考虑数组 a 和数据框 df

a = np.arange(4)
df = pd.DataFrame(np.repeat([1, 2, 3, 4], 4).reshape(4, -1))

print(a)

[0 1 2 3]

print(df)

0 1 2 3
0 1 1 1 1
1 2 2 2 2
2 3 3 3 3
3 4 4 4 4

您想将 pd.DataFrame.subaxis=0
一起使用这将使您的数组与 axis=0 或索引对齐,并逐列执行减法

print(df.sub(a, axis=0))

0 1 2 3
0 1 1 1 1
1 1 1 1 1
2 1 1 1 1
3 1 1 1 1

额外学分
使用 numpy 广播对齐轴

 print(df.values - a[:, None])

[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]

构建数据框

d1 = pd.DataFrame(df.values - a[:, None], df.index, df.columns)
print(d1)

0 1 2 3
0 1 1 1 1
1 1 1 1 1
2 1 1 1 1
3 1 1 1 1

关于 python Pandas : Using apply() to subtract a value from an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41386016/

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