I want to return only the row values (without column header or index column) based upon filter query. I am trying to write a function to this and have this so far:
def selector(name):
return df.loc[df['name'] == name][['name','color','number']].reset_index(drop = True)
I have a dataframe like this:
| Name | Color | Number |
0 | Mo | Red | 4 |
1 | Sue | Blue | 2 |
2 | Mat | Red | 6 |
3 | Mo | Green | 3 |
If I run my function:
selector('Mo')
I want it to return something like this:
0 | Mo | Red | 4
3 | Mo | Green | 3
But instead return something like this:
| Name | Color | Number
1| Mo | Red | 4
3| Mo | Green | 3
Name: df, dtype: object
How can I alter my function so that I can retrieve the results in the format that I would like?
CodePudding user response:
try this:
def selector(name):
return df.query('Name.eq(@name)')
selector('Mo')
>>>
Name Color Number
0 Mo Red 4
3 Mo Green 3
CodePudding user response:
Try this:
def selector(name):
return df.loc[df['Name'] == name].style.hide_index().hide_columns()
Output:
CodePudding user response:
I hope the following code snippet will clarify your doubts.
Let me know if you have any further questions about it.
import doctest
import pandas as pd
import numpy as np
def selector(df: pd.DataFrame, name: str) -> np.ndarray:
"""
>>> data = pd.DataFrame({
... 'name': ['Mo', 'Sue', 'Mat', 'Mo'],
... 'color': ['Red', 'Blue', 'Red', 'Green'],
... 'number': [4, 2, 6, 2]
... })
>>> selector(data, 'Mo')
array([['Mo', 'Red', 4],
['Mo', 'Green', 2]], dtype=object)
"""
condition = df["name"] == name
col_names = ["name", "color", "number"]
return df.loc[condition][col_names].values
if __name__ == "__main__":
doctest.testmod()