Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将数据帧转换为数字和dropna_Python_Pandas - Fatal编程技术网

Python 将数据帧转换为数字和dropna

Python 将数据帧转换为数字和dropna,python,pandas,Python,Pandas,我一直在使用: 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 1

我一直在使用:

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

您没有正确地调用
_numeric
。由于它只适用于列,如果要将其应用于所有列,则必须使用
pd.apply

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

应用于数值
然后
dropna

df.apply(lambda x :pd.to_numeric(x, errors ='coerce'),axis=1).dropna()
我会这样做:

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

这取决于数据。您是否尝试过?添加示例数据?我得到了以下错误:TypeError:(“to_numeric()得到了一个意外的关键字参数‘error’,‘发生在索引期’)完美。成功了!谢谢