简体   繁体   English

如何跳过 csv 文件 python 中的非数字行

[英]how to skip non numeric rows from csv file python

I have sample csv file with string values like below:我有示例 csv 文件,其字符串值如下所示:

1234, san@mail, IN, 001
, ram@mail, IN, 003
1235, john@mail, IN, 004 
san-ba, luios@mail, IN, 005 
undefined, thomas@mail, IN, 006

I need to skip the rows that having empty and non numeric in row[0] form the file.我需要跳过文件中 row[0] 中具有空和非数字的行。

Expected result:预期结果:

1234, san@mail, IN, 001
1235, john@mail, IN, 004 

You could try to convert the value into a float, and if it fails then you skip it:您可以尝试将值转换为浮点数,如果失败则跳过它:

for row in data:
    first_val = row[0]
    try:
        float(first_val)
    except ValueError:
        continue
    # here you use the row, knowing the first value is numerical
    print("this row has a numerical value in index 0")

You can convert categorial values to NaN, then drop NaNs您可以将分类值转换为 NaN,然后删除 NaN

import pandas as pd
import numpy as np

def categorial_to_nan(val):
    if str(val).isdigit():return val
    else:return np.NAN

Here is your dataset这是你的数据集

          id         email    x   y
0       1234      san@mail   IN   1
1        NaN      ram@mail   IN   3
2       1235     john@mail   IN   4
3     san-ba    luios@mail   IN   5
4  undefined   thomas@mail   IN   6
df['id'] = df['id'].map(categorial_to_nan)
df = df.dropna()
print('After')
print(df)

The Result结果

     id       email    x   y
0  1234    san@mail   IN   1
2  1235   john@mail   IN   4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM