gpt4 book ai didi

python - 如何替换数据框中的 Year 并在 Pandas 中将该值乘以 12

转载 作者:行者123 更新时间:2023-12-01 11:12:07 25 4
gpt4 key购买 nike

我需要用 12 替换 Year/years 的 String 并对该值执行乘法运算下面是示例数据框

 df = pd.DataFrame({'ten_in_Months' : ['1 year','2 years','3 years','40','50',],'paid_by' : ['hi', 
'foo', 'fat', 'cat','dog']})

我需要的是 1 年替换为 12 ,2 年替换为 24 ,3 年替换为 36

df['ten_in_months'].mul([12], axis=0)

我不知道如何使用正则表达式找到那一年替换并乘以 12 * ($)

最佳答案

如果您想将没有"year" 字符串的条目保留为月份,那么您可以使用以下代码

df['ten_in_Months'] = df['ten_in_Months'].apply(lambda x: int(x.split('year')[0])*12 if len(x.split('year')) > 1 else x)

关于python - 如何替换数据框中的 Year 并在 Pandas 中将该值乘以 12,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58823425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com