sat*_*ats 0 python pandas data-cleaning
我有一个想要清理的数据集。该数据集由 54 列和 315 行组成。对于其中一列,我想知道该列中的所有值是否都是数字。我做了以下事情:
work_sheet = pd.read_excel('2006_sale.xlsx', sheet_name='Sheet1')
df = work_sheet.copy()
Run Code Online (Sandbox Code Playgroud)
尝试1
for idx,val in enumerate(df['LotArea']):
if(not(str(val).isnumeric())): # Check if a value is numeric or not
df.at[idx,'LotArea'] = np.nan # If the value is not numeric then replace it with null
Run Code Online (Sandbox Code Playgroud)
尝试2
for idx,val in enumerate(df['LotArea']):
if(not(isinstance(val,float))): # Check if a value is numeric or not
df.at[idx,'LotArea'] = np.nan # If the value is not numeric then replace it with null
Run Code Online (Sandbox Code Playgroud)
这两种方法都有问题
不知何故,它将每个值检测为非数字,我的最终输出如下所示:

知道我哪里出错了吗?
不需要 for 循环来实现此目的。您可以使用 pd.to_numeric 方法,并通过将错误设置为“强制”,所有非数字值都将替换为 NaN。
df['LotArea'] = pd.to_numeric(df['LotArea'], errors='coerce')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6125 次 |
| 最近记录: |