在Python中转换年和月

vjhs03f7  于 2023-08-08  发布在  Python
关注(0)|答案(1)|浏览(97)

我正在使用如下的时间列:

import pandas as pd
 
# initialise data of lists.
data = {'Name':['Tom', 'nick', 'krish', 'jack'], 
        'Time':['3 years 4 months in role 20 years in company', '1 year 7 months in role 2 years 2 months in company',
                '2 years 1 month in role 7 years 2 months in company', '3 months in role 8 years 2 months in company']}
 
# Create DataFrame
df = pd.DataFrame(data)
 
# Print the output.
df

字符串
我需要将时间列拆分为两列time_in_role(months)和time_in_company(months)。并以月为单位计算适当的时间。
样品输入:


的数据
预期产出:



任何帮助都是感激的。

ffscu2ro

ffscu2ro1#

您可以使用正则表达式从字符串中获取年/月。之后就是简单的数学运算了

role = (
    df["Time"]
    .str.extract(r"(?:(?P<y>\d+) years?)?\s*(?:(?P<m>\d+) months?)? in role")
    .astype(float)
    .fillna(0)
)

company = (
    df["Time"]
    .str.extract(r"(?:(?P<y>\d+) years?)?\s*(?:(?P<m>\d+) months?)? in company")
    .astype(float)
    .fillna(0)
)

df["Time_in_Role(months)"] = (role["y"] * 12 + role["m"]).astype(int)
df["Time_in_Company(months)"] = (company["y"] * 12 + company["m"]).astype(int)
print(df)

字符串
印刷品:

Name                                                 Time  Time_in_Role(months)  Time_in_Company(months)
0    Tom         3 years 4 months in role 20 years in company                    40                      240
1   nick  1 year 7 months in role 2 years 2 months in company                    19                       26
2  krish  2 years 1 month in role 7 years 2 months in company                    25                       86
3   jack         3 months in role 8 years 2 months in company                     3                       98

相关问题