python pandas将文本中的数字提取到新列中

2024-09-28 09:35:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我在专栏A中有以下文本:

A   
hellothere_3.43  
hellothere_3.9

我想只提取到另一个新列B(A旁边),例如:

^{pr2}$

我使用:str.extract('(\d.\d\d)', expand=True)但是这个只复制了3.43(即精确的位数)。有没有办法让它更通用?在

非常感谢!在


Tags: 文本trueextractexpand位数str办法专栏
2条回答

我认为弦乐分裂和应用lambda是相当干净的。在

import pandas as pd

df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
df["B"] = df['A'].str.split('_').apply(lambda x: float(x[1]))

我没有做过任何适当的比较,但是在小测试中它似乎比regex解决方案快。在

使用正则表达式。在

例如:

import pandas as pd

df = pd.DataFrame({"A": ["hellothere_3.43", "hellothere_3.9"]})
df["B"] = df["A"].str.extract("(\d*\.?\d+)", expand=True)
print(df)

^{pr2}$

相关问题 更多 >

    热门问题