gpt4 book ai didi

python - 检查 Numpy 数组(和 Pandas DataFrame)中的所有元素并有选择地更改

转载 作者:行者123 更新时间:2023-12-01 01:57:34 29 4
gpt4 key购买 nike

假设我们有一个 numpy 二维数组(或 Pandas DataFrame),行和列的长度都是可变的。

是否有一种快速方法可以检查 numpy ndarray 或 pandas DataFrame 中的所有元素并剪辑到预先指定的最大值(如果任何元素大于预先指定的最大值),以更简单的为准?

最佳答案

pandas - 使用DataFrame.clip_upper :

np.random.seed(2018)
df = pd.DataFrame(np.random.randint(10, size=(5,5)))

print (df)
0 1 2 3 4
0 6 2 9 5 4
1 6 9 9 7 9
2 6 6 1 0 6
3 5 6 7 0 7
4 8 7 9 4 8

print (df.clip_upper(5))
0 1 2 3 4
0 5 2 5 5 4
1 5 5 5 5 5
2 5 5 1 0 5
3 5 5 5 0 5
4 5 5 5 4 5

Numpy - 使用numpy.clip :

np.random.seed(2018)
arr = np.random.randint(10, size=(5,5))
print (arr)
[[6 2 9 5 4]
[6 9 9 7 9]
[6 6 1 0 6]
[5 6 7 0 7]
[8 7 9 4 8]]

print (np.clip(arr, arr.min(), 5))
[[5 2 5 5 4]
[5 5 5 5 5]
[5 5 1 0 5]
[5 5 5 0 5]
[5 5 5 4 5]]

关于python - 检查 Numpy 数组(和 Pandas DataFrame)中的所有元素并有选择地更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49994206/

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