I have sample csv file with string values like below:
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.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.