'Filter rows from a DataFrame with matching pairs of strings
I need to filter rows from a dataframe that include matching pairs of strings. For example if the below instance when filtered only data for IDs 1 and 2 would be kept as 3 does not have a corresponding '3 Month' for the '0 Month' entry:
df = pd.DataFrame({'ID':[1,2,3,1,2,1], 'Period':['0 Month','0 Month','0 Month','3 Month','3 Month','6 Month']})
The OR operation can easily be used to filter for 2 strings, as below, but that does not drop the ID without the requisite pair.
df = df[(df["Period"].str.contains("0 Month")) | (df["Period"].str.contains("3 Month"))]
df
Therefore I'm attempting to use the AND operator to address this need but that is returning an empty dataframe:
df = df[(df["Period"].str.contains("0 Month")) & (df["Period"].str.contains("3 Month"))]
df
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
