DeepSea
DeepSea

Reputation: 305

Pandas dataframe returns False even if the values are equal

I've got an example:

+---------+---------+-------+
| 0       | 1       | Equal |
+---------+---------+-------+
| 3200    | 3200    | True  |
+---------+---------+-------+
| 3200.01 | 3200.01 | True  |
+---------+---------+-------+
| 8080.63 | 8080.63 | False |
+---------+---------+-------+
| 3408.81 | 3408.81 | True  |
+---------+---------+-------+
| 7080.01 | 7080.01 | False |
+---------+---------+-------+
| 2400.00 | 2400.00 | True  |
+---------+---------+-------+

The Equal column stores True/False values - True if column 0 and 1 are equal and False if not. The problem is that it does not always work - sometimes it adds False at random row even though it should be True and the numbers are equal

Column dtypes:

0                 float64
1                 float64
Equal               bool
dtype: object

I create Equal this way: df['Equal'] = df[0].ge(df[1])
I also tried: df['Equal'] = df[0].eq(df.iloc[:, -2])

Same problem all the time

It randomly returns False even though there shouldn't be False and now I am not sure if the values it returns as True are really correct or if it randomly gave True when there should be False, for example. How do I fix it?

Upvotes: 1

Views: 1153

Answers (1)

jezrael
jezrael

Reputation: 862551

First for equal use DataFrame.eq:

df['Equal'] = df[0].eq(df[1])

working like:

df['Equal'] = df[0] == df[1]

But because working with floats, there should be some accuracy problems, so use numpy.isclose:

df['Equal'] = np.isclose(df[0], df[1])

Upvotes: 2

Related Questions