python - Pandas - 用其他值替换值

标签 python pandas replace

我有一个像这样的 pandas DataFame :

cols                col1      col2      col3      col4
lines                                                  
l1                  0.004975  0.004975  0.865672  0.99005
l2                  0.004975  0.004975  0.865672  0.99005
l3                  0.004975  0.004975  0.990050  0.99005
l4                  0.004975  0.019900  0.865672  0.99005
l5                  0.004975  0.004975  0.990050  0.99005
l6                  0.004975  0.004975  0.865672  0.99005
l7                  0.004975  0.004975  0.865672  0.99005
l8                  0.004975  0.004975  0.865672  0.99005
l9                  0.004975  0.019900  0.865672  0.99005

我想将每个值替换为另一个值:如果该值 < 0.025,则应为 1,如果 > 0.0975,则应为 3,其他情况下应为 2。

这段代码完成了这项工作:

x = len(list(df.index))
y = len(list(df.columns))

for i in range(x):
    l = df.iloc[i]
    for j in range(y) :
        if l[j] < 0.025:
            l[j] = 1
        elif l[j] > 0.975:
            l[j] = 3
        else:
            l[j] = 2

但这非常丑陋,我想有一种更优雅和Pythonic的方式来做到这一点!我正在尝试使用 locmask 但目前没有结果。我还明确指出,行和列的数量和名称可能会有所不同,因此我正在编写适用于每种情况的代码。有人可以告诉我更好的代码吗?

最佳答案

使用numpy.select使用 DataFrame 构造函数:

m1 = df < 0.025
m2 = df > 0.975

df = pd.DataFrame(np.select([m1, m2], [1,3], default=2), index=df.index, columns=df.columns)
print (df)
      col1  col2  col3  col4
cols                        
l1       1     1     2     3
l2       1     1     2     3
l3       1     1     3     3
l4       1     1     2     3
l5       1     1     3     3
l6       1     1     2     3
l7       1     1     2     3
l8       1     1     2     3
l9       1     1     2     3

关于python - Pandas - 用其他值替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49171824/

相关文章:

python - 迭代 pandas 数据帧的索引

python - 将列添加到 SQLAlchemy 表

python - Pandas 列在一个组内排序,忽略其他列

javascript - 为什么 String.Prototype 替换在嵌套函数中不起作用?

jQuery为一个类的多个实例替换字符串中的字符

python - 如何使用空列表对pandas中的列进行json_normalize,而不会丢失记录?

python - 如何从列表中删除项目及其在其他列表中的关联项目

python - 多条件 Pandas 操作的嵌套 numpy.where 的替代方案?

python - .apply 与 Pandas 一起使用的正确方法是什么?

powershell - 如何使用 Powershell 脚本从主字符串中删除子字符串?