将复杂的str更改为在pandas Dataframe中浮动

问题描述 投票:1回答:1

我有一个数据集,其中包含有关公司资历的数据列:'9 years 9 months 14 days'格式的str。我用float循环用正则表达式将它们转换为for

for row in range(len(df)):
    target = df['seniority'][row]
    content = re.findall(r'\d+', target)
    content[0] = float(content[0])
    content[1] = (float(content[1]))/12
    content[2] = ((float(content[2]))/30)/12
    content = sum(content)
    df['seniority'][row] = content

有用。但是如果它存在的话,我对更有效和快速的方法感兴趣。

python regex string pandas dataframe
1个回答
2
投票

建立:

df = pd.DataFrame(
    {'sen': ['9 years 9 months 14 days', '2 years 4 months 12 days']
})

选项1: 用str.findall列出理解

df['seniority'] = [
    sum((float(x), float(y)/12, float(z)/365))
    for x, y, z in df.sen.str.findall(r'(\d+)').values
]

# Result

                        sen  seniority
0  9 years 9 months 14 days   9.788356
1  2 years 4 months 12 days   2.366210

选项2: str.extractdivsum

df.sen.str.extract(r'.*?(\d+).*?(\d+).*?(\d+)').astype(float).div([1, 12, 365]).sum(1)

0    9.788356
1    2.366210
dtype: float64

时序:

df = pd.concat([df]*10000).reset_index(drop=True)

%%timeit                                                  
for row in range(len(df)):                                
    target = df['sen'][row]                               
    content = re.findall(r'\d+', target)                  
    content[0] = float(content[0])                        
    content[1] = (float(content[1]))/12                   
    content[2] = ((float(content[2]))/30)/12              
    content = sum(content)
242 ms ± 1.67 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%%timeit                                                  
df['seniority'] = [                                   
    sum((float(x), float(y)/12, float(z)/365))        
    for x, y, z in df.sen.str.findall(r'(\d+)').values
]
29.9 ms ± 136 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit df.sen.str.extract(r'.*?(\d+).*?(\d+).*?(\d+)').astype(float).div([1,12, 365]).sum(1)
29 ms ± 143 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
© www.soinside.com 2019 - 2024. All rights reserved.