首页 > 解决方案 > 如何在熊猫中使用正则表达式在包含混合数据的df列中查找数字

问题描述

您知道如何转换此代码以获得更快的代码吗?在这段代码中,我只想取数字(十进制或整数)并拒绝列中存在的单词。事实上,在 a 列中,我可以找到数字和单词。谢谢!

 a=['a', '9','4.5','nnn', '3.4543', '2'] c=[1,10,5,4,4,7] 

df=pd.DataFrame(a,c) 
b =pd.Series(np.zeros(len(df)), name='b', index=df.index)    
    i = 0
for row in df.a:  
    if re.findall(r'(\d+[.]\d+)', str(row)):
        b.loc[i] = re.search(r'(\d+[.]\d+)', str(row)).group()
        
    elif re.findall(r'(\b\d+\b)', str(row)):  
        b.loc[i] = re.search(r'(\b\d+\b)', str(row)).group()

    else: 
        b.loc[i] = '9999'
    
    i = i + 1

for i in range(len(b)):
    b.loc[i]=float(b.loc[i])
    
df.a = b

我想获得 a=[9999, 9, 4.5,9999,3.4543, 2]

标签: pythonpandas

解决方案


使用 apply 和 assign 函数来创建一个新列:

重新进口

regnumber = re.compile(r'\d+(?:,\d*)?')

a=['a', '9','4.5','nnn', '3.4543', '2'] 
c=[1,10,5,4,4,7] 

df=pd.DataFrame({'a':a,'c':c}) 

df = df.assign(
    a = lambda x: x['a'].apply(lambda s: s if regnumber.match(s) else 9999)
)
print(df)

      a   c

   9999   1
      9  10 
    4.5   5
   9999   4
 3.4543   4
      2   7

推荐阅读