python - 将复杂的 str 更改为 pandas Dataframe 中的 float

标签 python regex string pandas dataframe

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

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

它有效。 但我对更有效、更快速的方法感兴趣(如果存在的话)。

最佳答案

设置:

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)

关于python - 将复杂的 str 更改为 pandas Dataframe 中的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51678823/

相关文章:

python - re.sub "(-)"失败

c - C 语言中字符串的结构空字符(\0) 问题

java.lang.NumberFormatException : For input string: "5

python - Scrapy-类型错误: this constructor takes no arguments

Python PRAW 包装器,逻辑问题

python - 帮助更正现有正则表达式以替换字符串值

正则表达式排除某些文件扩展名

python - 将python依赖提交到spark集群

python - tf-idf 向量化器在 char_wb 的特征词中有空格?

javascript - 在 JavaScript 中合并两个键=值对字符串