我的数据框很大。我试图通过遍历行和列来清理这些行。我发现这需要很长时间。因此,我尝试使用pd.apply(),但在实现时遇到了麻烦。
这是永远的尝试:
def elim_com(x):
try:
x.replace(',',' ')
except ValueError:
return x
def to_number(x):
try:
x=float(x)
return(x)
except ValueError:
return x
for row in range(df.shape[0]):
for column in range(0,dfconvertendum.shape[1],1):
try:
dfconvertendum.iloc[row,column]=elim_com(dfconvertendum.iloc[row,column])
except TypeError:
continue
except AttributeError:
continue
for row in range(df.shape[0]):
for column in range(0,df.shape[1],1):
try:
dfconvertendum.iloc[row,column]=to_number(dfconvertendum.iloc[row,column])
except TypeError:
continue```
Here is my attempt using apply:
```## Clean using apply
def elim_com(x):
try:
x.replace(',',' ')
except ValueError:
return x
def to_number(x):
try:
x=float(x)
return(x)
except ValueError:
return x
dfconvertendum=dfconvertendum.apply(elim_com)
dfconvertendum=dfconvertendum.apply(to_num)
目标是在当前有一个名为object的df dtype的情况下使用带浮点数的单个df。我也尝试过to_numeric,但是它以各种方式使事情变糟。我想要轻柔的清洁。我想保留所有不是逗号的数字,删除逗号,然后转换为浮点数。 最好!
答案 0 :(得分:1)
的确,您的代码效率不高,但并没有变得粗鲁。 pandas
的一大优点是您可以执行向量化的操作,速度非常快。假设您知道要转换为浮点型的列以及要删除逗号的哪些列,可以执行以下操作:
for col in df.columns:
df[col]=df[col].str.replace(',','').astype(float)
编辑:根据您的反馈更改答案
答案 1 :(得分:0)
我做到了。我的技巧是用np.NaN清理'N / A',然后执行pd.apply。这使我可以根据需要进行.sort_values()。
df=df.replace('N/A',np.NaN)
for col in df:
try:
df[col]=df[col].str.replace(',','').astype(float)
except ValueError:
continue
except AttributeError:
continue
except KeyError:
continue```