有没有方法在Python的data.table中使用regex(除了re.match)?
我想把py data.table中的一列转换成整数。这一列里有空格和其他不需要的字符,如果把这些去掉,就可以转换成整数了。不过我在py data.table中做不到这一点(而在polars、python和R data.table中可以做到):
# remove .00 if exists, minus after number etc.
df[:, update(weird_col = re.sub(r"\.[0-9]{0,2}|-", "", df[:, 'weird_col']))]
TypeError: expected string or bytes-like object
或者
df[:, update(weird_col = re.sub(r"\.[0-9]{0,2}|-", "", df['weird_col']))]
TypeError: cannot use a string pattern on a bytes-like object
1 个回答
2
我觉得简单的回答是“不可以”(re.match()
是dt.re
模块里唯一的函数)。
不过,你可以这样做:
from datatable import Frame, update, as_type
import re
wc = df["weird_col"].to_list()[0]
regex = r"\.[0-9]{0,2}|-"
df[:, update(weird_col = as_type(Frame([re.sub(regex, "", i) for i in wc ]), int))]
如果你想在pandas的系列上使用str.replace()
,并且是在数据表调用的情况下,正如@Nick所建议的,你可以这样做:
df[:, update(
weird_col = (
df["weird_col"]
.to_pandas()["weird_col"]
.str
.replace(r"\.[0-9]{0,2}|-","", regex=True)
.astype(int)
)
)]