gpt4 book ai didi

python - 将数据框转换为数字并删除

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:30 24 4
gpt4 key购买 nike

我一直在使用:

df = df.convert_objects(convert_numeric=True).dropna()

但由于它已被弃用,我需要将其替换为 to_numeric

我已经尝试过

df = pd.to_numeric
df = df.dropna()

示例数据:

Name  Race Fav Age  Weight Height Style Cut
John D K 23 120 23.5 DD RET
Rose Z U 33 110 47.9 KZ DEZ
James Z U FF UK NOT Z R

想要转换为删除非数字行

输出:

Name  Race Fav Age  Weight Height Style Cut
John D K 23 120 23.5 DD RET
Rose Z U 33 110 47.9 KZ DEZ

最佳答案

我会这样做:

In [399]: num_cols = df.columns[df.apply(pd.to_numeric, errors='coerce').any()]

In [400]: df[num_cols] = df[num_cols].apply(pd.to_numeric, errors='coerce')

In [401]: df = df[df.select_dtypes(['number']).notnull().all(1)]

In [402]: df
Out[402]:
Name Race Fav Age Weight Height Style Cut
0 John D K 23.0 120.0 23.5 DD RET
1 Rose Z U 33.0 110.0 47.9 KZ DEZ

In [403]: df.dtypes
Out[403]:
Name object
Race object
Fav object
Age float64
Weight float64
Height float64
Style object
Cut object
dtype: object

关于python - 将数据框转换为数字并删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47185432/

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