Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
仅当出现“故障”时才更换&引用;是python中数据帧列中的唯一值_Python_Regex_Replace - Fatal编程技术网

仅当出现“故障”时才更换&引用;是python中数据帧列中的唯一值

仅当出现“故障”时才更换&引用;是python中数据帧列中的唯一值,python,regex,replace,Python,Regex,Replace,我有一个正在使用的数据框,其中缺少的值用一个点(“.”)指定,我试图用“Not_Given”替换缺少的数据。但是,其他一些列在作为较长字符串一部分的字符串中有“.”。我已经设置了一个迷你数据框来测试以下替换方法: test_df = pd.DataFrame({"a": ["1", "2", "3", "4", "5"], "b": ["1.0", "2.0", "3.0", "4.0", "5.0"], "c": ["a", "b", "c", ".", "a.b"]}) test_df 打

我有一个正在使用的数据框,其中缺少的值用一个点(“.”)指定,我试图用“Not_Given”替换缺少的数据。但是,其他一些列在作为较长字符串一部分的字符串中有“.”。我已经设置了一个迷你数据框来测试以下替换方法:

test_df = pd.DataFrame({"a": ["1", "2", "3", "4", "5"], "b": ["1.0", "2.0", "3.0", "4.0", "5.0"], "c": ["a", "b", "c", ".", "a.b"]})
test_df
打印出以下数据框:

我编写了以下代码,试图替换单个“.”值(第3列的索引3):

这将返回输出:

显然,这将替换数据帧中遇到的每个“.”,因此值1.0将替换为1 NOT_Given0

我还尝试了以下代码:

for col in ["a", "b", "c"]:
    test_df[col] = test_df[col].str.replace("\.{1,1}", "Not_Given")
仍然具有与上述相同的输出


如果只有一个“.”值而没有其他字符,是否有一种方法可以替换?

我想,可能是一个简单的表达式,例如

^\s*\.\s*$
在这里可能行

我们还添加了
\s*
,以防在
之前或之后出现空格

试验 输出
如果您希望简化/更新/探索表达式,将在的右上面板中进行解释。如果您感兴趣,可以查看匹配步骤或在中修改它们。调试器演示了如何逐步使用一些示例输入字符串并执行匹配过程


尝试熊猫功能:

test_df.replace({'.': 'Not_Given'})
结果:

   a    b          c
0  1  1.0          a
1  2  2.0          b
2  3  3.0          c
3  4  4.0  Not_Given
4  5  5.0        a.b
您可以使用
“^\.$”

或者干脆

test_df[col][ test_df[col] == '.' ] = "Not_Given"


以下是几种不同的惯用解决方案:

将numpy导入为np
作为pd进口熊猫
df[df.eq('.')]=np.NaN
df=df.map({'.':np.NaN})
df=df.replace(to_replace='.',value=np.NaN)
df=df.replace({'.':np.NaN})

为什么不使用
NaN
来表示缺少的数据?你能分享更多你的节目吗?可能还需要进行其他设计更改。我没有生成正在使用的数据集。他们决定用“.”来指定缺少的数据,我只是想用一个简化的例子来计算代码。这没有问题,你可以简单地用
NaN
替换句点。这是最好的答案。我看不出在这种情况下需要正则表达式。
test_df.replace({'.': 'Not_Given'})
   a    b          c
0  1  1.0          a
1  2  2.0          b
2  3  3.0          c
3  4  4.0  Not_Given
4  5  5.0        a.b
test_df[col].str.replace("^\.$", "Not_Given")
test_df[col][ test_df[col] == '.' ] = "Not_Given"
import pandas as pd

test_df = pd.DataFrame({"a": ["1", "2", "3", "4", "5"], "b": ["1.0", "2.0", "3.0", "4.0", "5.0"], "c": ["a", "b", "c", ".", "a.b"]})

for col in ["a", "b", "c"]:
    #test_df[col] = test_df[col].str.replace("^\.$", "Not_Given")
    test_df[col][ test_df[col] == '.' ] = "Not_Given"
print(test_df)
df[df['c'] == '.'] = 'Not_Given'