Extracting data from various sheets with Python

Python is often called a glue language. This is due to the fact that a plethora of interface libraries and features have been developed over time — driven by its widespread usage and an amazing, extensive open-source community. Those libraries and features give straightforward access to different file formats, but also data sources (databases, webpages, and APIs).

This story focuses on the extraction part of the data. Next week’s story will then dive a little deeper into analyzing the combined data to derive meaningful and exciting insights. But don’t let that stop you from analyzing the data yourself.

What you will learn:

· Extracting data from Google Sheets

· Extracting data from CSV files

· Extracting data from Excel files

Who is this article for:

· Python beginners

· People who have to wrangle data regularly

As this article is intended as a code-along article, you should have your development environment (I recommend Jupyter Notebook/Lab) set up and start a new Notebook. You can find the source code and files here.

Situation:

In today’s story, I will take you into a fictitious but probably oddly familiar situation. You are to combine data from various sources to create a report or run some analyses.

Disclaimer: The following example and data used are entirely fictitious

You are tasked with figuring out how to increase your sales team’s performance. In our hypothetical situation, potential customers have rather spontaneous demand. When this happens, your sales team puts an order lead** **into the system. Your sales reps then try to get set up a meeting that occurs around the time the order lead was noticed. Sometimes before, sometimes after. Your sales reps have an expense budget and always combine the meeting with a meal for which they pay. The sales reps expense their costs and hand the invoices to the accounting team for processing. After the potential customer has decided whether or not they want to go with your offer, your diligent sales reps track whether or not the order lead converted into a sale.

For your analysis, you have access to the following three data sources:

· 100.000 order leads (Google Sheets)

· ~50.000 meal invoices (Excel file)

· List of companies and sales reps responsible for them (CVS file)

Get Google Sheets Data:

Accessing Google Sheets turns out to be the most complicated of the three because it requires you to set up some credentials for using the Google Sheets API. You could, in theory, scrape a publicly available Google Sheet (i.e., pull the source HTML code), but you would have to do a lot of data manipulation with tools like Beautiful Soup to turn that HTML dump into something useful. I did try this, but the results were a mess and not worth the effort. So API it is. Additionally, we will use gspread for more seamless conversion to a pandas DataFrame.

Obtain OAuth2 credentials

Head to Google Developers Console and create a new project (or select an existing one). Click the “Create Project” button. If your company uses Google Mail, you might want to change into your private account to avoid potential permission conflicts.

Choose a name for your project (the name does not matter, I call mine Medium Data Extraction)

**Click APIs & Services **and head to library

Enable Google Sheets API. Click on the result and click enable API on the following page.

Create a service account & key file. A service account is a dedicated account used for programmatic access with limited access rights. Service accounts can and should be set up by project with as specific permissions as possible and necessary for the task at hand.

Create a JSON (another file format) key file. For Role select “Project -> Viewer.”

If you have not set the Role in the previous step, do it now.

Note: Setting “Viewer” is somewhat restrictive. If you want to create google sheets programmatically, you’ll have to choose a different setting

Your private JSON key file will then be ready for download or downloaded automatically. I suggest renaming the file to Medium_Data_Extraction_Key.jsonand moving the file to the folder of your Jupyter Notebook as this will make the following examples work seamlessly. The JSON file contains your credentials for the recently created service account.

Perfect. You are almost done.

Download the data

First, you will have to download and install additional packages by running the following commands in your Notebook.

!pip install gspread
!pip install oauth2client

Secondly, you will have to make sure to move your previously created JSON key file to the folder from which you are running the Jupyter notebook, if it is not already there. Alternatively, you could specify a different GOOGLEKEYFILE path.

from oauth2client.service_account import ServiceAccountCredentials
import gspread
import pandas as pd

scope = [
    'https://www.googleapis.com/auth/spreadsheets',
]

GOOGLE_KEY_FILE = 'Medium_Data_Extraction_Key.json'

credentials = ServiceAccountCredentials.from_json_keyfile_name(GOOGLE_KEY_FILE, scope)
gc = gspread.authorize(credentials)

wokbook_key = '10HX66PbcGDvx6QKM8DC9_zCGp1TD_CZhovGUbtu_M6Y'
workbook = gc.open_by_key(wokbook_key)
sheet = workbook.get_worksheet(0)
values = sheet.get_all_values()
sales_data = pd.DataFrame(values[1:],columns=values[0])

WORKBOOK_KEY is the workbook id of the Google Sheet I prepared for this session.

WORKBOOK_KEY = '10HX66PbcGDvx6QKM8DC9_zCGp1TD_CZhovGUbtu_M6Y'

The sheet is publicly available. You need to change the WORKBOOK_KEY if you want to download different data. The id can typically be found between the last two backslashes in the Google Sheets at question URL.

Get the CSV data

We can either download the CSV data the traditional way from the repo or by using the following snippet. Again you might have to install the missing requests package like this (run in your notebook):

!pip install requests

import requests
url = 'https://raw.githubusercontent.com/FBosler/Medium-Data-Extraction/master/sales_team.csv'
res = requests.get(url, allow_redirects=True)
with open('sales_team.csv','wb') as file:
    file.write(res.content)
sales_team = pd.read_csv('sales_team.csv')

The beauty of CSV data is that Python / Pandas can deal with it out of the box. For Excel, there are additional libraries required.

Get the Excel Data

Before we get started, you will most likely have to install openpyxl and xlrd, which enables your Pandas to also open Excel sheets.

!pip install openpyxl
!pip install xlrd

After having done that, we get the Excel data in the same fashion and load it into another DataFrame.

url = 'https://github.com/FBosler/Medium-Data-Extraction/blob/master/invoices.xlsx?raw=true'
res = requests.get(url, allow_redirects=True)
with open('invoices.xlsx','wb') as file:
    file.write(res.content)
invoices = pd.read_excel('invoices.xlsx')

Done! You have created three different Pandas data frames and can access them in the same Jupyter notebook:

· sales_data

· sales_team

· invoices

Stay tuned for next week’s article, when we look into how to combine these data frames and analyze the data.

#python #data-science

What is GEEK

Buddha Community

Extracting data from various sheets with Python
Ray  Patel

Ray Patel

1619518440

top 30 Python Tips and Tricks for Beginners

Welcome to my Blog , In this article, you are going to learn the top 10 python tips and tricks.

1) swap two numbers.

2) Reversing a string in Python.

3) Create a single string from all the elements in list.

4) Chaining Of Comparison Operators.

5) Print The File Path Of Imported Modules.

6) Return Multiple Values From Functions.

7) Find The Most Frequent Value In A List.

8) Check The Memory Usage Of An Object.

#python #python hacks tricks #python learning tips #python programming tricks #python tips #python tips and tricks #python tips and tricks advanced #python tips and tricks for beginners #python tips tricks and techniques #python tutorial #tips and tricks in python #tips to learn python #top 30 python tips and tricks for beginners

Siphiwe  Nair

Siphiwe Nair

1620466520

Your Data Architecture: Simple Best Practices for Your Data Strategy

If you accumulate data on which you base your decision-making as an organization, you should probably think about your data architecture and possible best practices.

If you accumulate data on which you base your decision-making as an organization, you most probably need to think about your data architecture and consider possible best practices. Gaining a competitive edge, remaining customer-centric to the greatest extent possible, and streamlining processes to get on-the-button outcomes can all be traced back to an organization’s capacity to build a future-ready data architecture.

In what follows, we offer a short overview of the overarching capabilities of data architecture. These include user-centricity, elasticity, robustness, and the capacity to ensure the seamless flow of data at all times. Added to these are automation enablement, plus security and data governance considerations. These points from our checklist for what we perceive to be an anticipatory analytics ecosystem.

#big data #data science #big data analytics #data analysis #data architecture #data transformation #data platform #data strategy #cloud data platform #data acquisition

Arvel  Parker

Arvel Parker

1593156510

Basic Data Types in Python | Python Web Development For Beginners

At the end of 2019, Python is one of the fastest-growing programming languages. More than 10% of developers have opted for Python development.

In the programming world, Data types play an important role. Each Variable is stored in different data types and responsible for various functions. Python had two different objects, and They are mutable and immutable objects.

Table of Contents  hide

I Mutable objects

II Immutable objects

III Built-in data types in Python

Mutable objects

The Size and declared value and its sequence of the object can able to be modified called mutable objects.

Mutable Data Types are list, dict, set, byte array

Immutable objects

The Size and declared value and its sequence of the object can able to be modified.

Immutable data types are int, float, complex, String, tuples, bytes, and frozen sets.

id() and type() is used to know the Identity and data type of the object

a**=25+**85j

type**(a)**

output**:<class’complex’>**

b**={1:10,2:“Pinky”****}**

id**(b)**

output**:**238989244168

Built-in data types in Python

a**=str(“Hello python world”)****#str**

b**=int(18)****#int**

c**=float(20482.5)****#float**

d**=complex(5+85j)****#complex**

e**=list((“python”,“fast”,“growing”,“in”,2018))****#list**

f**=tuple((“python”,“easy”,“learning”))****#tuple**

g**=range(10)****#range**

h**=dict(name=“Vidu”,age=36)****#dict**

i**=set((“python”,“fast”,“growing”,“in”,2018))****#set**

j**=frozenset((“python”,“fast”,“growing”,“in”,2018))****#frozenset**

k**=bool(18)****#bool**

l**=bytes(8)****#bytes**

m**=bytearray(8)****#bytearray**

n**=memoryview(bytes(18))****#memoryview**

Numbers (int,Float,Complex)

Numbers are stored in numeric Types. when a number is assigned to a variable, Python creates Number objects.

#signed interger

age**=**18

print**(age)**

Output**:**18

Python supports 3 types of numeric data.

int (signed integers like 20, 2, 225, etc.)

float (float is used to store floating-point numbers like 9.8, 3.1444, 89.52, etc.)

complex (complex numbers like 8.94j, 4.0 + 7.3j, etc.)

A complex number contains an ordered pair, i.e., a + ib where a and b denote the real and imaginary parts respectively).

String

The string can be represented as the sequence of characters in the quotation marks. In python, to define strings we can use single, double, or triple quotes.

# String Handling

‘Hello Python’

#single (') Quoted String

“Hello Python”

# Double (") Quoted String

“”“Hello Python”“”

‘’‘Hello Python’‘’

# triple (‘’') (“”") Quoted String

In python, string handling is a straightforward task, and python provides various built-in functions and operators for representing strings.

The operator “+” is used to concatenate strings and “*” is used to repeat the string.

“Hello”+“python”

output**:****‘Hello python’**

"python "*****2

'Output : Python python ’

#python web development #data types in python #list of all python data types #python data types #python datatypes #python types #python variable type

Ray  Patel

Ray Patel

1619510796

Lambda, Map, Filter functions in python

Welcome to my Blog, In this article, we will learn python lambda function, Map function, and filter function.

Lambda function in python: Lambda is a one line anonymous function and lambda takes any number of arguments but can only have one expression and python lambda syntax is

Syntax: x = lambda arguments : expression

Now i will show you some python lambda function examples:

#python #anonymous function python #filter function in python #lambda #lambda python 3 #map python #python filter #python filter lambda #python lambda #python lambda examples #python map

Gerhard  Brink

Gerhard Brink

1620629020

Getting Started With Data Lakes

Frameworks for Efficient Enterprise Analytics

The opportunities big data offers also come with very real challenges that many organizations are facing today. Often, it’s finding the most cost-effective, scalable way to store and process boundless volumes of data in multiple formats that come from a growing number of sources. Then organizations need the analytical capabilities and flexibility to turn this data into insights that can meet their specific business objectives.

This Refcard dives into how a data lake helps tackle these challenges at both ends — from its enhanced architecture that’s designed for efficient data ingestion, storage, and management to its advanced analytics functionality and performance flexibility. You’ll also explore key benefits and common use cases.

Introduction

As technology continues to evolve with new data sources, such as IoT sensors and social media churning out large volumes of data, there has never been a better time to discuss the possibilities and challenges of managing such data for varying analytical insights. In this Refcard, we dig deep into how data lakes solve the problem of storing and processing enormous amounts of data. While doing so, we also explore the benefits of data lakes, their use cases, and how they differ from data warehouses (DWHs).


This is a preview of the Getting Started With Data Lakes Refcard. To read the entire Refcard, please download the PDF from the link above.

#big data #data analytics #data analysis #business analytics #data warehouse #data storage #data lake #data lake architecture #data lake governance #data lake management