温馨提示:本文翻译自stackoverflow.com,查看原文请点击:pandas - Extracting numeric value from a string of a dataframe's column and replace the string with that nume
pandas python-3.6

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

发布于 2020-03-31 23:38:52

说如果列'A'包含前三行的值:4.5 mg,5.8 mg,6.3 mg我想要的是:提取后,它应类似于:4.5,5.8,6.3

有什么帮助吗?另外,我不知道如何在stackoverflow中显示我的数据框。因此,对于这个问题的身体形成,我真的感到很抱歉。

查看更多

提问者
Ayan Chowdhury
被浏览
13
jezrael 2020-01-31 19:55

使用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)