Home > Blockchain >  Check if value in column is an integer and return True
Check if value in column is an integer and return True

Time:06-07

I have a dataframe with a quantity column. How do I check which values in that column are integers?

I have tried

if df['quantity'].map(type) == int:
        True
else:
        item_no = df['item_number'].tolist()
        print(item_no)

which gives me the following ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Ideally, I would like the output to be a list of the item numbers where the quantity is not an integer.

CodePudding user response:

If you want to check if there are any Python ints in your column, try this:

df['quantity'].map(type).eq(int).any()

CodePudding user response:

Assuming you just want the indices where the value is an int, the following should suffice df.index[(df['quantity'].map(type)==int)].tolist()

CodePudding user response:

If you want to identify the non integers you can use:

df[df['quantity'].map(type).ne(int)]

Or

df[~df['quantity'].apply(lambda x: isinstance(int, x))]

Or for non numbers:

df[pd.to_numeric(df['quantity'], errors='coerce').isna()]

CodePudding user response:

The following code returns a list of the item numbers for where the 'quantity' column does not contain an integer

q = df.loc[~df['quantity'].str.isdigit(), 'item_num'].tolist()
print(q)
  • Related