Python Forum

Full Version: Returning Specific Value in Files
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello, I'm new to Python and I've been going through some online tutorials. While quite a few all go through how to read files, I find that none really explained well how to return a specific value, if that's the way to describe it.

Say I have an Excel File with such:
Name | Weight | Day
Tom | 150 | Monday
Tom | 149 | Tuesday
Tom | 148 | Wednesday
John | 150 | Monday
John | 151 | Tuesday
John | 152 | Wednesday
Kevin | 150 | Monday
Kevin | 148 | Tuesday
Kevin | 146 | Wednesday

I sort of have a basic understanding how to do the loc and iloc. But is there a way where I can "search" by Name and Day, to find out Weight? Like if I had it search Tom on Monday, what is his weight?
Make and effort to post code that can be executed.
Not all here use Pandas,then it get even more difficult to help when can not run code
Example Pandas has many ways to do this:
import pandas as pd
from io import StringIO

data = StringIO('''\
Name|Weight|Day
Tom|150|Monday
Tom|149|Tuesday
Tom|148|Wednesday
Joh|150|Monday
John|151|Tuesday
John|152|Wednesday
Kevin|150|Monday
Kevin|148|Tuesday
Kevin|146|Wednesday''' )

df = pd.read_csv(data, sep="|")
Now can test code.
>>> df.head()
   Name  Weight        Day
0   Tom     150     Monday
1   Tom     149    Tuesday
2   Tom     148  Wednesday
3   Joh     150     Monday
4  John     151    Tuesday
Quote:Like if I had it search Tom on Monday, what is his weight?
For this can use Boolean indexing
Quote:The operators are: | for or, & for and, and ~ for not. These must be grouped by using parentheses.
>>> w = df[(df['Name']=='Tom') & (df['Day']=='Monday')]
>>> w
  Name  Weight     Day
0  Tom     150  Monday
>>> int(w.Weight)
150
Then can test out different combo.
People that are under 149 on a Wednesday.
>>> # Under 149
>>> df[df['Weight'] < 149]
    Name  Weight        Day
2    Tom     148  Wednesday
7  Kevin     148    Tuesday
8  Kevin     146  Wednesday

>>> # Under 149 on a Wednesday
>>> df[(df['Weight'] < 149) & (df['Day']=='Wednesday')]
    Name  Weight        Day
2    Tom     148  Wednesday
8  Kevin     146  Wednesday