【发布时间】:2021-09-02 21:32:58
【问题描述】:
考虑以下DataFrame:
df = pd.DataFrame({'a':['123','667','323'],
'b':['8000','1. 300', '56'],
'c':['11','apple', '100']})
# a b c
# 0 123 8000 11
# 1 667 1. 300 apple
# 2 323 56 100
如果它是一串数字,我想将数据类型更改为 int。正则表达式很简单:
pattern = '^\d+$'
df.apply(lambda x: x.str.match(pattern, flags=re.IGNORECASE))
如何将任何匹配的列的数据类型更改为int(本例中的列a)?列名不一致,因此我无法对其进行硬编码。这里需要applymap吗?
【问题讨论】:
-
请发布预期输出
-
为什么不只是
df[col].astype(int, errors='ignore')?