python - 检查 Column 是否超过特定值并替换

标签 python pandas numpy

我使用类似于下面代码的一长串代码来检查多列数据框

我需要检查该列是否有任何大于 Eg 的值。 1000. 如果 >1000 其错误值,则将其设置为“0”

b=1000
a = np.array(df['E8'].values.tolist()); df['E8'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E9'].values.tolist()); df['E9'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E10'].values.tolist()); df['E10'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E11'].values.tolist()); df['E11'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E12'].values.tolist()); df['E12'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E13'].values.tolist()); df['E13'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E20'].values.tolist()); df['E20'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E21'].values.tolist()); df['E21'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E29'].values.tolist()); df['E29'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E28'].values.tolist()); df['E28'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E30'].values.tolist()); df['E30'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E31'].values.tolist()); df['E31'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E32'].values.tolist()); df['E32'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E36'].values.tolist()); df['E36'] = np.where(a > b, 0, a).tolist()
a = np.array(df['E37'].values.tolist()); df['E37'] = np.where(a > b, 0, a).tolist()

有没有一种简单有效的方法呢。

最佳答案

您可以使用列名列表简化您的解决方案:

np.random.seed(2021)

cols = ['E8','E9','E10', 'E37']
df = pd.DataFrame(np.random.randint(0, 2000, size=(10, 4)), columns=cols) 

b = 1000
df[cols] = np.where(df[cols] > b, 0, df[cols])

print (df)
    E8   E9  E10  E37
0    0    0   57    0
1  621    0   44    0
2  830  669    0  349
3  152    0  502  198
4    0   70  545  613
5    0  257    0    0
6    0    0  410    0
7  944    0   63    0
8  656    0  822  379
9    0    0  632    0

关于python - 检查 Column 是否超过特定值并替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66451513/

相关文章:

python - 将函数应用于 3D numpy 数组

python - OpenCV 将图像读取为 3 channel 图像,而 PIL 将图像读取为 1 channel 图像

python - TensorFlow tf.data.Dataset 和分桶

python - 根据字典选择 Pandas 数据框的行

python - 为什么 tqdm.pandas() 不工作? - 如何解决PanelGroupBy导入问题

python - 在数据框中对一列进行求和,同时保留其他列

python - squeeze = True 在groupby中做什么?

numpy - 获取 xarray 数据集的非 nan 值的坐标

python - 如何使用 ssh-ed25519 作为 pysftp 的 key 设置主机 key 文件

python - 将多个相同的 SQLite 查询合并为一个