Hea*_*ing 5 python numpy pandas
我想使用 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.
Run Code Online (Sandbox Code Playgroud)
例如,我的数据帧中的第一行是 [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)
Run Code Online (Sandbox Code Playgroud)
但这里棘手的事情是我需要遍历我的 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
Run Code Online (Sandbox Code Playgroud)
您想要使用pd.DataFrame.subwithaxis=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
Run Code Online (Sandbox Code Playgroud)
使用numpy广播来对齐轴的额外学分
print(df.values - a[:, None])
[[1 1 1 1]
[1 1 1 1]
[1 1 1 1]
[1 1 1 1]]
Run Code Online (Sandbox Code Playgroud)
构造数据框
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2465 次 |
| 最近记录: |