如何将字符串(如年龄)转换为列中的单个值?

how to transform strings (like age) to single value in colums?

我是 PANDAS 的新手,我找不到像这样转换的方法:

 0 AGE
 1 82 years 03 months 11 days
 2 54 years 06 months 10 days
 3 23 years 03 months 09 days
 4 60 years 02 months 13 days

对此:

0 AGE
1 82
2 54
3 23
4 60

提前致谢

剥离字符串(删除字符串中的前导 space,以防万一),拆分它,然后取第一项,使其成为整数:

df["AGE"] = df["AGE"].apply(lambda x : int(x.strip().split()[0]))

只需申请Timedeltas

df['AGE']=df.AGE.astype('timedelta64[Y]')

另一种方法。 这里我们使用正则表达式 extracting 字符串开头的数字。

df["AGE"] = df["AGE"].str.extract('(^\d+)')

输出

    0   AGE
0   1   82
1   2   54
2   3   23
3   4   60