从dataframe中获取字符串中的数字可以通过正则表达式来实现。以下是一个示例代码:
import pandas as pd
import re
# 创建一个包含字符串的dataframe
df = pd.DataFrame({'text': ['abc123', 'def456', 'ghi789']})
# 使用正则表达式提取字符串中的数字
df['numbers'] = df['text'].apply(lambda x: re.findall(r'\d+', x))
print(df)
输出结果为:
text numbers
0 abc123 [123]
1 def456 [456]
2 ghi789 [789]
在上述代码中,我们使用re.findall()
函数和正则表达式r'\d+'
来提取字符串中的数字。r'\d+'
表示匹配一个或多个连续的数字。df['text'].apply(lambda x: re.findall(r'\d+', x))
将对每个字符串应用正则表达式,并返回一个包含匹配到的数字的列表。最后,我们将提取到的数字列表存储在新的列numbers
中。
这种方法适用于从dataframe中的字符串中提取任意形式的数字。
领取专属 10元无门槛券
手把手带您无忧上云