Python Forum
Median of the age row - tsv file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Median of the age row - tsv file
#1
Problem: Code a program that opens a tsv file and calculated the mean age of female.

I opened it with this code:
import csv
with open("047.tsv") as tsvfile:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    for line in tsvreader:
        print (line[1:])
And it prints something like this:

['age', 'gender']
['20', 'female']
['30', 'female']
['21', 'female']
['23', 'female']
['30', 'female']
['25', 'female']
['13', 'female']
['19', 'female']
['16', 'female']
['25', 'female']
['20', 'female']
['25', 'male']
['27', 'male']
['43', 'male']

How do I continue to only get the median of the "age" row?
for number in age:
??

Do I need to import statistics to make it easier to get the mean? (with statistics.mean())
I need to define number and age first too.. I'm not really sure how to start with this
Reply
#2
Before your loop you should create an empty list, potentially calling it female_ages. Inside your for-loop, you'll want to check the gender, and if it's female, add the age to your list (it looks like you'll probably need to turn that age into an int / float, before adding it to the list). After the loop, you can use the function you asked about on that list you populated.
Reply
#3
I would suggest you to use Pandas for such i/o operations.
Pandas has a lot of helper and customizable functions, e.g. read_csv:

import pandas as pd
data = pd.read_csv('047.tsv', sep='\t')
data.age.median() # compute median of the age column, 
# or data['age'].median(), data['age'].mean() etc. 
Reply
#4
Pandas is overkill for this, especially if it's an intro Python course, where they would likely not allow third party libraries. This can be done easily in Python without any imports, or with standard imports that come with Python. (statistics comes standard in some Python 3 version.)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Calculate median for school grades per subject siki 1 1,932 May-10-2021, 11:41 AM
Last Post: jefsummers
  Help on Creating Program to find the Median and Mode by hand EvanCahill 3 2,935 Jul-19-2018, 06:17 PM
Last Post: woooee
  Masked median filters Jim421616 0 2,859 Aug-24-2017, 01:30 AM
Last Post: Jim421616

Forum Jump:

User Panel Messages

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