在python中使用“where”更改数据帧中的值

2024-09-25 00:36:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图更改那些数据类型为数值的列中的值。但是我的代码不起作用

数据帧名称:mergedDF

for c, dtype in zip(mergedDF.columns,mergedDF.dtypes):
    if dtype == np.int64:
        mergedDF[c].where(mergedDF[c]> 0,1)

它基本上没有改变什么。当我尝试分配变量名时,它将所有内容更改为1

if dtype == np.int64:
    mergedDF[c] = mergedDF[c].where(mergedDF[c]> 0,1)

输入:

col1   col2   col3
1       2       0
4       0       1
2       2       0

预期产出:

col1   col2   col3
1       1       0
1       0       1
1       1       0

我的原始表中只有2个数据类型

case_history            object     # text column
cleaned_text            object     # text column
401k deduction           int64     # 0-10
assistance manual        int64     # 0-10
assistance quick         int64     # 0-10

Tags: textifobjectnpcolumnwherecol2col3