gpt4 book ai didi

python - 检查数据框中是否存在正值

转载 作者:行者123 更新时间:2023-12-01 07:47:12 24 4
gpt4 key购买 nike

我有数据框:

A B C D
1 0 0 2
0 1 0 0
0 0 0 0

我需要选择所有大于 0 的值并将它们放入列表中。如果行不包含任何正值 0 应写入列表。

因此,给定数据帧的输出应如下所示:

 [1,2,1,0]

如何解决这个问题?

最佳答案

这是一个您可以使用的简单循环(循环遍历 df.values 为我们提供作为数组的行):

output = []

for ar in df.values:
nonzeros = ar[ar > 0]
# If nonzeros is not empty proceed and extend the output
if nonzeros.size:
output.extend(nonzeros)
# If not add 0
else:
output.append(0)

print(output)

返回:

[1, 2, 1, 0]

关于python - 检查数据框中是否存在正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56408009/

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