【问题标题】:Extracting the integers from a column of strings从一列字符串中提取整数
【发布时间】:2019-07-10 15:00:15
【问题描述】:

我有 2 个数据帧:longdf 和 shortdf。 Longdf 是“主”列表,我需要基本上匹配从 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]

【问题讨论】:

  • 我很困惑,为什么你的shortdflongdf完全一样?
  • 好问题:我开始在这里提出一个更长的问题,但将其分解,并且从未更改过变量名。

标签: python pandas for-loop


【解决方案1】:

如果我理解正确,您希望获取一系列包含整数的字符串,并删除所有不是整数的字符。为此,您不需要 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)
})

【讨论】:

    猜你喜欢
    • 2020-07-20
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 2013-03-09
    相关资源
    最近更新 更多