如何将现有数据框列的值替换为 re.search 循环中的值?
这是我的研究循环。
for i in dataset['col1']:
clean = re.search('(nan|[0-9]{1,4})([,.][0-9]{1,4})?', i)
print(clean.group())
这是样本数据集(dataset)
year col1
1 2001 10.563\D
2 2002 9.540\A
3 2003 4.674\G
4 2004 3.2754\u
5 2005 nan\x
最佳答案
您可以使用 Series.apply将自定义函数应用于 dataset["col1"]
。或者,你可以使用 Series.str.replace 更好。用替换字符串替换模式。
试试这个:
def func(i):
clean = re.search('(nan|[0-9]{1,4})([,.][0-9]{1,4})?', i)
return clean.group()
dataset["col1"] = dataset["col1"].apply(func)
或者更好,
df["col1"] = df["col1"].str.replace(r'(.*?)(\\.*?$)', r"\1")
输出:
>>> print(dataset)
year col1
0 2001 10.563
1 2002 9.540
2 2003 4.674
3 2004 3.2754
4 2005 nan
关于python - 从 re.search 循环替换数据框列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60965138/