Home > Net >  For loop to remove non-strings from a list
For loop to remove non-strings from a list

Time:12-23

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']

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

CodePudding user response:

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']
  • Related