enter image description here我有一个关于年龄的数据框架:
AgeInYears
0 1年
1 1岁
2 2年
3、3周
4 2年
5个半月
6-3周
7 3周
我必须将它转换为int中的age:
AgeInYears
0 1
1 1
2 2
3 0.06
4 2
5 0.08
6 0.06 7 0.06
首先,我开始替换所有包含"years“的animals['AgeInYears'].str.replace('years','').str.replace('year','')
但我不知道如何计算几个星期或几个月。Lambda函数?
发布于 2018-11-05 05:12:20
您可以创建条件,如果是weeks,则获取该值并除以52:
df = pd.DataFrame({'AgeInYears':['1 year', '1 year', '2 years', '3 weeks', '2 years',
'1 month', '3 weeks', '3 weeks']})
# split the column into 2
df = df['AgeInYears'].str.split(expand=True)
df[0] = df[0].astype(int)
0 1
0 1 year
1 1 year
2 2 years
3 3 weeks
4 2 years
5 1 month
6 3 weeks
7 3 weeks
然后,您可以根据自己的条件使用np.select
:
conditions = [
(df[1].str.contains('year')),
(df[1].str.contains('week')),
(df[1].str.contains('month'))
]
choices = [
df[0],
df[0]/52,
df[0]/12
]
df['newValue'] = np.select(conditions,choices,default=np.nan)
0 1 newValue
0 1 year 1.000000
1 1 year 1.000000
2 2 years 2.000000
3 3 weeks 0.057692
4 2 years 2.000000
5 1 month 0.083333
6 3 weeks 0.057692
7 3 weeks 0.057692
https://stackoverflow.com/questions/53145312
复制相似问题