作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我想使用 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.sub
与 axis=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/
我是一名优秀的程序员,十分优秀!