Python 如何更改数据帧上的数据类型?

Python 如何更改数据帧上的数据类型?,python,regex,Python,Regex,这是我之前使用正则表达式的数据帧 我使用正则表达式删除s,如下所示 50s 20s 30s 40s 但这样的结果并不好。如下 import re def split_it(data): return re.findall('(\d+)',data) df_plot['age'] = df_plot['age'].apply(lambda x:split_it(x)) 那么,如何转换数据帧上的数据类型(仅限数字)?您可以这样做 解决方案1: 更改功能并保持第二行不变 [50] [3

这是我之前使用正则表达式的数据帧

我使用正则表达式删除s,如下所示

50s
20s
30s
40s
但这样的结果并不好。如下

import re

def split_it(data):
    return re.findall('(\d+)',data)

df_plot['age'] = df_plot['age'].apply(lambda x:split_it(x))
那么,如何转换数据帧上的数据类型(仅限数字)?

您可以这样做

解决方案1: 更改功能并保持第二行不变

[50]
[30]
[50]
[20]
解决方案2 保持函数不变,并更改第二行

def split_it(data):
    return re.findall('(\d+)',data)[0]

df_plot['age'] = df_plot['age'].apply(lambda x:split_it(x))

我觉得有点太复杂了。如果数据总是带有最后一个“s”,那么就不需要正则表达式,您可以使用
df_plot['age'][:-1]
首先,您的代码将无法工作。要使它按您的意愿工作,您需要像这样更改它
df_plot['age'].str[:-1]
。第二,如果没有OP中的任何其他细节,我认为最好尽量保持代码不变。但是,如果这是唯一的使用案例,我同意你的观点,使用正则表达式并不需要你的教学。这真的很有帮助!
def split_it(data):
    return re.findall('(\d+)',data)

df_plot['age'] = df_plot['age'].apply(lambda x:split_it(x)).str[0]