Python Forum
Returning Specific Value in Files
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Returning Specific Value in Files
#1
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?
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Plotting climate data with NetCdf files for a specific region with coordinates fyec 3 5,412 Jun-27-2018, 12:34 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020