Search code examples
pythonsearchrow

Python search row for letters


I have a table of data that has a row of data as strings, but I am looking to convert the row to floats with this line:

uomorig_df['Conversion'] = uomorig_df['Conversion'].astype(float, errors = 'raise')

and it keeps erroring out, so I am thinking there is an alphanumeric character somewhere in just that row and I am hoping to identify that row, how can I find a letter in a row of data?

I was looking to try RegEx or Pandas... but kind of got lost.


Solution

  • Using a list comprehension, you can pretty easily loop over the indices and values of uomorig_df['Conversion'] with enumerate(), convert the values to a string, and check if those values are valid floats with .replace('.', '', 1).isdigit():

    import pandas as pd
    
    # example dataframe
    uomorig_df = pd.DataFrame({
        "Conversion": [1, 2, 3, 4, 'A', 6, 7, 8]
    })
    
    letters = [val for val in enumerate(uomorig_df['Conversion'])
               if not str(val[1]).replace('.', '', 1).isdigit()]
    print(letters)  # => [(4, 'A')]
    

    The result of the list comprehension is a tuple in the form of (index, value), where index is the index of the alphabetic value in the row, and value is the nonnumerical value.