【问题标题】:how to transform strings (like age) to single value in colums?如何将字符串(如年龄)转换为列中的单个值?
【发布时间】:2020-03-10 00:26:10
【问题描述】:
我是 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
提前致谢
【问题讨论】:
标签:
python
string
pandas
transform
【解决方案1】:
另一种方法。
这里我们是extracting使用正则表达式的字符串开头的数字。
df["AGE"] = df["AGE"].str.extract('(^\d+)')
输出
0 AGE
0 1 82
1 2 54
2 3 23
3 4 60
【解决方案2】:
剥离字符串(去掉字符串中的前导空格,以防万一),拆分,然后取第一项,使其成为整数:
df["AGE"] = df["AGE"].apply(lambda x : int(x.strip().split()[0]))
【解决方案3】:
只需申请Timedeltas
df['AGE']=df.AGE.astype('timedelta64[Y]')