python pandas将文本中的数字提取到新列 [英] python pandas extracting numbers within text to a new column

查看:103
本文介绍了python pandas将文本中的数字提取到新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 A中有以下文本:

I have the following text in column A:

A   
hellothere_3.43  
hellothere_3.9

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

I would like to extract only the numbers to another new column B (next to A), e.g:

B                      
3.43   
3.9

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

I use: str.extract('(\d.\d\d)', expand=True) but this copies only the 3.43 (i.e. the exact number of digits). Is there a way to make it more generic?

非常感谢!

推荐答案

使用正则表达式.

例如:

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)

输出:

                 A     B
0  hellothere_3.43  3.43
1   hellothere_3.9   3.9

这篇关于python pandas将文本中的数字提取到新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆