Append to list each line of CSV file row if row is have numeric values

Hello Experts…Good day…Need some little help.
I would like to append the values from csv row.
But i want them stop appending of row is non numeric.

import csv
file = r"csv file link"
x = []
y = []
csv_f = csv.reader(file, delimiter=",")
for row in csv_f:
   if row.isnumeric() == True:
         x.append(row[0])
         y.append(row[1])

But I got an error…‘list’ object has no attribute ‘isnumeric’…please help…thanks

A row in a csv reader object is a list of strings. You need to check each item in the list individually. For example, to check if the first two items in the row are numeric you can do:

if all(col.isnumeric() for col in (row[0], row[1])):

Note that there is no need to check equality with True.

2 Likes

Thank you so much…How about let say the x list append append only max values of 700…then it will stop appendig…thanks

Wait a min…when run debug mode in pycharm i saw list x,y have no appended values :frowning:

Some clarification can be helpful. What values do you want to append? First and second character or word? Do you want to look for digit in whole row or only in first two words/characters? What you consider numeric?

I am sharing some portion of csv file…please check the image.
2 things, i want to stop appending if number hit 700…or if the code detect none numeric values. In the image are → “”“”.
First col is X and the 2nd col is Y…thanks in advance

X Y
2 1.15E-10
4 1.15E-09
8 1.15E-11
9 1.15E-12
. .
. .
700 1.15E-13

Your file contains some numbers with scientific notation (1.15E-10, for example). This will be a problem; str.isnumeric() will not correctly identify these as floats. I suggest using a more sophisticated tool to read the file, like pandas.

You could also do it by calling float on them directly inside a try/except:

try:
    y.append(float(row[1]))
except ValueError:
    break

This will break out of the for loop and stop any additional values from being appended to the lists.

4 Likes

Don’t post pictures.

This numeric value must be in first column (before first comma)? Or first and second?Does row A,B,C,4 contains numeric value or not? Do you want append int or str?

You are using str.isnumeric, does that mean this is accepted behaviour:

>>> nums = ['123', '一二三', '1²']    # second item is 123 in Kanji
>>> for num in nums:
...     print(num.isnumeric())
...
True
True
True 
2 Likes

Oh this one works…thanks alot…You save my day ")

Thanks for the reminder…already took out the picture…thanks

The best way to wrangle with .csv files is by using pandas library. Consult the documentation to find specifically what you need:

import pandas as pd
from pathlib import Path

df = pd.read_csv(Path("path", "to", "the", "file.csv"))
df = df.loc[df.str.isnumeric()]
num_list = df.to_list()