首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从一列字符串中提取整数

从一列字符串中提取整数
EN

Stack Overflow用户
提问于 2019-07-10 23:00:16
回答 1查看 40关注 0票数 2

我有两个数据帧: longdf和shortdf。longdf是‘master’列表,我需要基本上匹配从shortdf到Longdf的值,那些匹配的值,替换其他列中的值。longdf和shortdf都需要大量的数据清理。

我们的目标是达到df的“目标”。我正在尝试使用for循环,其中我希望1)提取df单元格中的所有数字,以及2)从单元格中去掉空白/单元格空间。首先:为什么这个for循环不能工作?第二:有没有更好的方法呢?

import pandas as pd

a = pd.Series(['EY', 'BAIN', 'KPMG', 'EY'])
b = pd.Series(['   10wow this is terrible data8 ', '10/ USED TO BE ANOTHER NUMBER/ 2', ' OMG 106 OMG ', '    10?7'])
y = pd.Series(['BAIN', 'KPMG', 'EY', 'EY' ])
z = pd.Series([108, 102, 106, 107 ])

goal = pd.DataFrame
shortdf = pd.DataFrame({'consultant': a, 'invoice_number':b})
longdf = shortdf.copy(deep=True)
goal = pd.DataFrame({'consultant': y, 'invoice_number':z})

shortinvoice = shortdf['invoice_number']
longinvoice = longdf['invoice_number']

frames = [shortinvoice, longinvoice]
new_list=[]

for eachitemer in frames:
    eachitemer.str.extract('(\d+)').astype(float) #extracing all numbers in the df cell
    eachitemer.str.strip() #strip the blank/whitespaces in between the numbers
    new_list.append(eachitemer)

new_short_df = new_list[0]
new_long_df = new_list[1]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-10 23:08:25

如果我理解正确的话,您希望获取一系列包含整数的字符串,并删除所有不是整数的字符。为此,您不需要使用for循环。相反,您可以用一个简单的正则表达式来解决它。

b.replace('\D+', '', regex=True).astype(int)

返回:

0    108
1    102
2    106
3    107

正则表达式用一个空字符串替换所有不是数字的字符(用\D表示),删除所有不是数字的字符。.astype(int)将序列转换为整数类型。您可以像往常一样将结果合并到您的最终数据帧中:

result = pd.DataFrame({
    'consultant': a, 
    'invoice_number': b.replace('\D+', '', regex=True).astype(int)
})
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56973530

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档