Comparing pandas dataframe column with String resulting in False

Viewed 32

I am trying to compare dataframe column id with string value contract number

JSON file:

[
    {
        "id": "ee123-abc"
    }
]
df = pd.DataFrame.from_dict(data)
contract_num = 'ee123-abc'

if (df.id == contract_num).any():
    print("Matching")
else:
    print("Not matching")

I tried converting df.c_w_id.astype(str), but still the if condition goes to Not Matching. Please advise how to compare a dataframe column with String value.

1 Answers

So you have the following:

import numpy as np
import pandas as pd

json = [
    {
        "id": "ee123-abc"
    }
]

df = pd.DataFrame(json)

contract_num = 'ee123-abc'

print(df)
>>> [{'id': 'ee123-abc'}]

This is the condition you need:

print(not df[df['id'] == contract_num].empty)
>>> True

Therefore:

if not df[df['id'] == contract_num].empty:
    print("Matching")
else:
    print("Not matching")

I hope it helps :)

Related