【发布时间】:2016-12-29 19:26:23
【问题描述】:
我想使用 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() 做到这一点?
【问题讨论】:
-
[[1,1,1,1],[2,2,2,2],[3,3,3,3],[4,4,4,4]]不是数据帧。这是一个列表。 -
我只是没有写出整个 pd.Dataframe() 位。我只是想快速展示数据框的外观,而无需添加所有代码。
-
好吧,为什么不把
temp_arr变成一个系列,然后从你的行中减去呢?