Sunday, 9 August 2015

Airline Routing

Airline routes are more complex and need to get update our airline route charts to avoid any accidents. The below python program allows you to manipulate the given set of data and find out the distribution of different flight distances.

We need to calculate Geo distance which is quite different from our normal distance calculation as the former deals with longitudes and latitudes.

import matplotlib.pyplot as plt
import csv 
import geo_distance


We are working with two different input dataset1 - airports.dat to get airport details and dataset2 - routes.dat to get route details. And now we've to calculate geo_distance from both these data and record it in a list distance[]

d = open("airports.dat.txt")
latitudes = {}
longitudes = {}
distances = []
for row in csv.reader(d):
  airport_id = row[0]
  latitudes[airport_id] = float(row[6]) 
  longitudes[airport_id] = float(row[7])
f = open("routes.dat")
for row in csv.reader(f):
  source_airport = row[3]
  dest_airport = row[5]
if source_airport in latitudes and   dest_airport in latitudes:
  source_lat = latitudes[source_airport]
  source_long = longitudes[source_airport]
  dest_lat = latitudes[dest_airport]
  dest_long = longitudes[dest_airport]        
distances.append(geo_distance.distance(source_lat,source_long,dest_lat,dest_long))

Histogram:

Let's create a histogram with hist()


plt.hist(distances, 100, facecolor='b')
plt.xlabel("Distance (km)") 
plt.ylabel("Number of flights")
.

  







Charts in Python [matplotlib]

A picture speaks thousand words. Any data which is expressed in terms of graph, pie chart are so easy to be conceived by the audience.

Objective:

To draw a bar-graph using matplotlib in python.

Procedure:

step 1: import matplotlib package,

                  import matplotlib.pyplot as plt

step 2: draw the bar graph with the values (vote)

                  plt.bar(range(len(counts)), counts.values(), align='center')

step 3: print bar graph

                  plt.show()


Output:



Working with Strings,Tuples and Dictionary

As we all know python is one of the most used programming language in terms of developing. We will see how important it is in analytic perspective with the below program.

Case Study:

Suppose you're a greengrocer, and you run a survey to see what radish varieties your customers prefer the most. You have your assistant type up the survey results into a text file on your computer, so you have 300 lines of survey data each line consists of a name, a hyphen, and then a radish variety.


Objective:

What's the most popular radish variety?
What are the least popular?
Did anyone vote twice?

Approach:

Step 1: First we will read the input file 'line-by-line' using 'for' and 'in' function.
       
                          for line in open("radishsurvey.txt"):

Step 2: Then we clean our data in 3 steps,
 
     Step 2.1 -  by stripping away all junks such as null characters in the EOL.

line1 = line.strip()

 Step 2.2 -  by splitting Customer Name with the Radish type voted.
 
                            name, vote = line1.split(" - ")

Step 2.3 -   by Capitalizing Radish types so that all entries follow same pattern of Radish Names.
 
                         vote = vote.strip().capitalize()

Step 3: Create a new list voted[],


Step 4: If the voter name is not existing in the list, add the name to "voted[]" list. Else print a warning saying "Customer has already voted"


Step 5: Create a dictionary counts{},


Step 6: Read the 'Radish Type' and assign it as key. Count the number of times the same Radish Type has been voted and assign it to Value.


if vote not in counts:
    counts[vote] = 1
else:
# Increment the vote count
    counts[vote] = counts[vote] + 1

Till Step 6 we created a program to get the unique voters, a table(dictionary) with Radish type and corresponding voted counts.


Step 7: Create a user defined function to get the maximum and minimum voted radish type.

Step 7.1: To calculate the most popular radish type,


def find_winner(counts):
 winner = ""
 pre_vote = 0
  for vote in counts:
   if counts[vote] >= pre_vote:
    winner = vote
    pre_vote = counts[vote]
return winner, pre_vote
pprint(counts)  
winner= find_winner(counts)
print "Most popular radish type is:",winner
 


Step 7.2: To calculate the least popular radish type,



def find_loser(counts):
 loser = ""
 loser,pre_vote = find_winner(counts)
 for vote in counts:
  if counts[vote] <= pre_vote:
   loser = vote
   pre_vote = counts[vote]
return loser, pre_vote
pprint(counts)  
loser= find_loser(counts)
print "Most non popular radish type is:",loser


Output:




Note - download the base used for this survey from the link - RadishType_DB