gpt4 book ai didi

Python-将数据框除以数字列表,包括零

转载 作者:行者123 更新时间:2023-11-30 22:38:40 27 4
gpt4 key购买 nike

我有一个包含 10 列的数据框。我想用不同的数字来划分每一列。如何将数据框除以数字列表?列表中还有零,如果除以零,我希望该列中的数字为 1。如何做到这一点?

谢谢

最佳答案

给定数据帧df和列表lst作为numpy数组

df = pd.DataFrame(np.random.rand(10, 10))

lst = np.array([1, 0, 1, 0, 1, 0, 1, 0, 1, 0])

然后我们可以使用mask来过滤。通过使用掩码,我们可以使用 bool 切片来获取 lst 中具有相应零值的列。我们还可以使用 ~m 和切片轻松访问非零。

m = lst == 0

# assign the number 1 to all columns where there is a zero in lst
df.values[:, m] = 1

# do the division in place for all columns where lst is not zero
df.values[:, ~m] /= lst[~m]

print(df)

0 1 2 3 4 5
0 0.195316 1.0 0.988503 1.0 0.981752 1.0
1 0.136812 1.0 0.887689 1.0 0.346385 1.0
2 0.927454 1.0 0.733464 1.0 0.773818 1.0
3 0.782234 1.0 0.363441 1.0 0.295135 1.0
4 0.751046 1.0 0.442886 1.0 0.700396 1.0
5 0.028402 1.0 0.724199 1.0 0.047674 1.0
6 0.680154 1.0 0.974464 1.0 0.717932 1.0
7 0.636310 1.0 0.191252 1.0 0.777813 1.0
8 0.766330 1.0 0.975292 1.0 0.224856 1.0
9 0.335766 1.0 0.093384 1.0 0.547195 1.0

关于Python-将数据框除以数字列表,包括零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43458454/

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