python - 应用正则表达式创建新列 - isdigit() 与 isnumeric()

标签 python regex python-3.x pandas dataframe

我有一个如下所示的数据框

data_file= pd.DataFrame({'pid':[1,1.5,6.557657,'ABCD','1+','TRACE']})

如下图所示

enter image description here

我想要的是创建两个新列 value_as_numbervalue_as_string

这是我尝试过的

value_as_string = data_file['pid'].str.extract('(\D+)') # this chops of the `1` from `1+` which isn't expected.

value_as_string 的输出如下所示

enter image description here

value_as_number = ~data_file['pid'].str.extract('(\D+)') # results in error as shown below

TypeError: bad operand type for unary ~: 'float'

我也试过了,但也没用

data_file['pid'].str.isnumeric()
data_file['pid'].str.digit()

我希望我的输出如下所示。单独的数字列(如 1、2、1.5、4.5)和单独的数字、字符和符号混合列(1+、ABCD、测试)等

enter image description here

最佳答案

您可以使用pd.to_numericdf.where

data_file['num'] = pd.to_numeric(data_file['pid'],errors='coerce')

data_file['alpha'] = data_file['pid'].where(data_file['num'].isnull())

       pid       num  alpha
0        1  1.000000    NaN
1      1.5  1.500000    NaN
2  6.55766  6.557657    NaN
3     ABCD       NaN   ABCD
4       1+       NaN     1+
5    TRACE       NaN  TRACE

最后您可以使用 fillna('') 但尽量不要对数字列执行此操作。

关于python - 应用正则表达式创建新列 - isdigit() 与 isnumeric(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57346033/

相关文章:

python - 生成 lambda 函数组合的组合

python - 尝试将 xarray 写入 netcdf 时出现 "ValueError: chunksize cannot exceed dimension size"

python - 如何使用2to3翻译目录中的所有文件

regex - TCL:逻辑运算符在正则表达式中定义的变量中不起作用

python - 可选的结束符号和使用正则表达式捕获的几个单词

regex - 用操纵模式替换多个模式

python 在函数之间传递列表

python - TypeError : object. __init__() 没有参数

python - 为反向遗传关系创建序列化器

python - 如何将字符串解释为字节?