Difference between '&' and 'and'

Hi All!

Currently working on the “Petal Power Inventory” Task within the “DATA MANIPULATION WITH PANDAS” module (link below).
https://www.codecademy.com/paths/data-science/tracks/dscp-data-manipulation-with-pandas/modules/dscp-hands-on-with-pandas/projects/pandas-inventory-proj

For task 5 I have written out the below code:

import codecademylib3 import pandas as pd import numpy as np inventory = pd.read_csv('inventory.csv') print(inventory.head(10)) staten_island = inventory[0:10] staten_island['product_request'] = staten_island.product_description seed_request = inventory[(inventory.location == 'Brooklyn') and (inventory.product_type == 'seeds')] print(seed_request)

This seems to throw an error when i run it and it seems to be down to the ‘and’. When I instead use the ‘&’ operator it seems to run fine.

import codecademylib3 import pandas as pd import numpy as np inventory = pd.read_csv('inventory.csv') print(inventory.head(10)) staten_island = inventory[0:10] staten_island['product_request'] = staten_island.product_description seed_request = inventory[(inventory.location == 'Brooklyn') & (inventory.product_type == 'seeds')] print(seed_request)

Why does the ‘and’ operator not work in this case? To my understand the ‘&’ operator is for bit operations so the ‘and’ operation should make more sense here. Maybe there is a rule for working with Data Frames that I’m unaware of that would explain this? Thanks in advance for any potential help on my question!

Wrote a couple of replies about this before that might be helpful-

There is a rule but it’s from Python itself rather than pandas. A dataframe or series has multiple elements and Python’s operators are not set-up to work on multiple elements by default. However, using the fact most operators in Python rely on methods of an object, e.g. the comparison operators- https://docs.python.org/3/reference/datamodel.html?emulating-container-types#object.lt the pandas module overloads these methods for frame/series objects to make the operators work on every element on the frame/series. However and is a bit different and does not use a method so it has no simple method to overload it.

The & operator is a bitwise operation rather than a logical operation but it does have a method associated with it .__and__ (this is for &, not for and). Pandas can overload this operator to allow element-wise logical and operations. If on some occasion you actually want element-wise bitwise operations there are functions like np.bitwise_and, equally there is np.logical_and if you’d rather not use the operator at all.

2 Likes