|col1|col2|col3|col4|
|nan |nan | fr |rt. |
|nan|MK1 |fg. |aa. |
|nan.|MA1 |fl. |f2|
Now we have a three rows with header col1,col2….
I want to extract row using certain value
Expected output : MK1|fg|aa
MA1|f1 |f2
I used df[(df.values==‘MK1).any(axis=1)
For multiple value df[(df.values ==‘MK1’) && (df.values==‘MA1)]
It is giving 0 rows with header .can someone help me to achieve this ? Please don’t use loc or iloc
Thanks in advance
CodePudding user response:
You should use OR |
instead of AND &
because you are looking for MK1
OR MA1
in a column.
df[(df["col2"] == "MK1") | (df["col2"] == "MA1")]
CodePudding user response:
A better way to do this is below. Has the advantage if number of matching values is many you can just pass a list of possible matches rather than writing a condition for each
matches=['MK1','MA1']
df=df[df["Description_x"].apply(lambda x: x in matches)]
or in a single line
df=df[df["Description_x"].apply(lambda x: x in ['MK1','MA1'])]
or
MK1row =df[df["Description_x"].apply(lambda x: x=='MK1')]
MK2row =df[df["Description_x"].apply(lambda x: x=='MK2')]