Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

For loop to remove non-strings from a list

I am trying to iterate over the list elemets and remove non-string items. However the loop is failing and removing strings as well.

currency.unique()

array([‘CADCAD’, ‘CADCHF’, ‘CADEUR’, ‘CADGBp’, ‘CADUSD’, ‘CADNOK’, nan,
‘CADMXN’], dtype=object)

Forex_ticker=list(currency.unique())

for item in Forex_ticker:
    if type(item)!='str':
        print(item,type(item),Forex_ticker)
        Forex_ticker.remove(item)
    else:
        continue

CADCAD <class ‘str’> [‘CADCAD’, ‘CADCHF’, ‘CADEUR’, ‘CADGBp’, ‘CADUSD’, ‘CADNOK’, nan, ‘CADMXN’]
CADEUR <class ‘str’> [‘CADCHF’, ‘CADEUR’, ‘CADGBp’, ‘CADUSD’, ‘CADNOK’, nan, ‘CADMXN’]
CADUSD <class ‘str’> [‘CADCHF’, ‘CADGBp’, ‘CADUSD’, ‘CADNOK’, nan, ‘CADMXN’]
nan <class ‘float’> [‘CADCHF’, ‘CADGBp’, ‘CADNOK’, nan, ‘CADMXN’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Forex_ticker
['CADCHF', 'CADGBp', 'CADNOK', 'CADMXN']

>Solution :

You’re removing from the list while iterating, which is always a bad idea. To remove the nan values from the array, you can use pandas.isnull function:

import numpy as np
import pandas as pd

a = np.array(
    [
        "CADCAD",
        "CADCHF",
        "CADEUR",
        "CADGBp",
        "CADUSD",
        "CADNOK",
        np.nan,
        "CADMXN",
    ],
    dtype=object,
)

a = a[~pd.isnull(a)]
print(a)

Prints:

['CADCAD' 'CADCHF' 'CADEUR' 'CADGBp' 'CADUSD' 'CADNOK' 'CADMXN']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading