从数据框列的字符串中提取数值并将该字符串替换为该数值

Extracting numeric value from a string of a dataframe's column and replace the string with that numerical value

假设列 'A' 包含前 3 行的值:4.5 毫克、5.8 毫克、6.3 毫克 我想要的是:提取后应该是这样的: 4.5 , 5.8 , 6.3

有什么帮助吗? 此外,我不知道如何在 Whosebug 中显示我的数据框。所以真的很抱歉问题的正文

使用 Series.str.extract 转换为浮动:

df = pd.DataFrame({'A':'4.5 mg, 5.8 mg, 6.3 mg'.split(', ')})

df['new'] = df['A'].str.extract(r'(\d\.\d)+').astype(float)

如果可能的话一些整数值:

df['new'] = df['A'].str.extract(r"(\d*\.?\d+|\d+)").astype(float)

print (df)
        A  new
0  4.5 mg  4.5
1  5.8 mg  5.8
2  6.3 mg  6.3

如果可能,通过第一个空格使用 split 使用 Series.str.splitstr 来索引第一个值:

df['val'] = df['A'].str.split().str[0].astype(float)

还有一种可能。如果您在数值和单位之间有一个 space,将会起作用。

df['val'] = df['A'].apply(lambda x: x.split(' ')[0]).astype(float)
print (df)
        A  val
0  4.5 mg  4.5
1  5.8 mg  5.8
2  6.3 mg  6.3