Blogs

Blogs

Parameters in Tableau

Parameters in Tableau are referred to as containers of values used to calculate and effectively enter values not present in the original dataset. These parameters can include workbook variables like dates, a string of text, a number, or a calculated field which can be used to replace the constant value in a filter or calculation. We can also add conditions and put in a range of values for which we want to create a parameter. After that, we then incorporate these values into our reports and dashboards so we can see each change. In this tutorial, we’ll demonstrate what the Date Field Parameter is. Date Field Parameters in Tableau Working with Date Parameters in Tableau helps to give users the flexibility to change date levels from years to months, from months to weeks, or from weeks to days. We’ll show this with an example below; Step one Open Tableau on your computer and open a new worksheet; we will use the Superstore Dataset. Now, drag the Order Date to the Row Pane on the working area and drag the Sales to the Text under the cards. Ensure to select Table under Show Me, so it won’t be displayed as a chart. Step Two We have each sales value per year, what we need to do is create our Parameter. We will do that by clicking the arrow icon in the top left corner and selecting create parameter option as shown in the image below. The dialogue box appears and we will put in a Name(Dates Params) and select the datetype as a string. Select the list option and put in each of the values(Year, Quarter, Month, Week, Day) and press Enter Key. Follow what we did in the image below and select OK. You will see your Parameter below the Measure Fields and right-click on it. Select Show Parameters which will be displayed on your working area for easy navigation. Step Three The Parameters we created aren’t in use yet except that we have to reference them in a calculated field. In this calculated field, we will select each of the fields (Year, Quarter, Month, Weeks, and Day) to match their actual calculation, so it can display each sale we have per year, quarter, month, week, and day respectively. 1CASE [Dates Params ] 2 3WHEN “Year” THEN STR(YEAR([Order Date])) 4 5WHEN “Quarter” THEN STR(YEAR([Order Date]))+”/Q”+ DATENAME(‘quarter’, [Order Date]) 6 7WHEN “Month” THEN DATENAME(‘month’,[Order Date])+””+STR(YEAR([Order Date])) 8 9WHEN “Week” THEN “Week” + STR(DATEPART(‘week’,[Order Date])) 10 11WHEN “Day” THEN STR(DATE([Order Date])) 12 13END   After this, we will click on the Show Me tab to change the view from Table to chart. Thereby, we can navigate to different charts using our Parameters. If you found this post helpful, let us know in the comments box.

Blogs

How to Connect Python with SQL Server Database Using Pyodbc

In this tutorial, we will look at how to connect Python with SQL server using Pyodbc Library. The Pyodbc library is an open-source Python module that makes accessing ODBC databases simple. It is also a community-supported software. We have other Database Management Systems(DMS) that also work with ODBC. These Database Management Systems include; Oracle, MS Access, IBM Db2, MS SQL Server, and MySQL. How to Get Started Step1 The first thing we need to do is to install the Pyodbc Library in order to create a connection between Python and the SQL Server. Installation We can install Pyodbc with the PIP Package Installer. pip install pyodbc Step 2 Now, we need to create a connection using the Pyodbc library we just installed. The credentials we need to use are; Server Name, Database Name, and the table we want to connect to. 1#import the pyodbc library 2import pyodbc 3 4#create a connection with the pyodbc using the needed credentials 5the_conn = pyodbc.connect(‘Driver={SQL Server};’ 6 ‘Server=my-project.xxxxxxxxxxxxxs.amazonaws.com;’ 7 ‘Database=myData;’ 8 ‘Trusted_Connection=yes;’) 9#create an instance and execute using the select command to retrieve your table details 10cursor = the_conn.cursor() 11cursor.execute(‘SELECT * FROM your_table_name’) 12#loop through the result to obtain your table data 13for j in cursor: 14 print(j)   How to Connect Pyodbc with Pandas You can also use Pandas library to connect to SQL Server along with the Pyodbc. The Pandas library is well known for its flexibility and ease of use. You can follow the steps below to use the library with Pandas. Install Pandas We can install Pandas with the Pip Package or can be installed with Anaconda or Miniconda as it is part of the Anaconda distribution:   Install with PIP 1pip install pandas Install with Conda 1conda install pandas From Pandas DataFrame to SQL Here, we will read data from our computer using Pandas to a Dataframe. After then, we convert the Dataframe to a SQL Table. The SQLAlchemy create engine will also be used in the script to pass in our connection URL. 1#import our library 2import pyodbc 3import pandas as pd 4import urllib 5 6#import create engine from sqlalchemy 7from sqlalchemy import create_engine 8 9#this is what the credentials we’ll be passing in looks like 10server = ‘my-project.xxxxxxxxxxxxxs.amazonaws.com’ 11database = ‘myData’ 12username = ‘admin’ 13password = ‘xxxxxxxx’ 14 15#the file we are bringing in, we read it with pandas 16df= pd.read_csv(‘Python_Project.csv’) 17 18#we use the urllib_parse_quote to read in all our credentials to a url string 19quoted = urllib.parse.quote_plus(“DRIVER={ODBC Driver 17 for SQL Server}; SERVER=my-project.xxxxxxxxxxxxxs.amazonaws.com;DATABASE=myData;UID=admin;PWD=xxxxxxxx”) 20engine = create_engine(‘mssql+pyodbc:///?odbc_connect={}’.format(quoted)) 21#we convert the file to SQL Table 22df.to_sql(‘provide_the_name_for_our_table’, schema=’dbo’, con = engine)   From SQL to Pandas DataFrame Earlier we learned how to convert a Pandas DataFrame to SQL Table. We can also read SQL data with Pandas and convert it to a DataFrame. 1#import our libraries 2import pandas as pd 3import pyodbc 4 5#create a connection using your credentials 6the_conn = pyodbc.connect(‘Driver={SQL Server};’ 7 ‘Server=my-project.xxxxxxxxxxxxxs.amazonaws.com;’ 8 ‘Database=myData;’ 9 ‘Trusted_Connection=yes;’) 10#we use the pandas read sql_query along with our connection instance to retrieve our table 11df = pd.read_sql_query(‘SELECT * FROM students’, the_conn) 12#we then print our data 13print(df.head(n=5))  

Blogs

How to Work with JSON Data in Python

JSON stands for JavaScript Object Notation which was derived from the subdivision of Javascript Programming Language dealing with Object Literal Syntax. It is used for representing structured data and is very effective for transmitting and receiving data between a server and web application. JSON is a built-in package that came with Python. This package is very good for encoding and decoding JSON data. Now, we’ll learn about 2 different terms in JSON, we have Serialization and Deserialization. Serialization can be referred to as a way of encoding JSON, and how we use the dump() method for writing data to files. Deserialization on the other hand means the conversion of JSON objects into their respective Python objects where we use the load() and loads() method to change the JSON encoded data into Python Objects. We will go further to carry out some implementation below; How to Convert JSON TO Dictionary We will look into how we can convert our JSON data into a dictionary format by using the JSON module and the JSON.loads() method. An example of how to convert a JSON to a dictionary is shown below; 1 #import json module 2import json 3 4#our json string 5user = ‘{“member”: “registered”, “status”: [“paid”, “active”]}’ 6#we use the .loads() method to convert our data 7user_dict = json.loads(user) 8#here we print the dictionary 9print(user_dict) 10# result: {“member”: “registered”, “status”: [“paid”, “active”]} 11 12print(user_dict[‘status’]) 13# Output: [“paid”, “active”] How to Convert Dictionary to JSON We can do a vice-versa of converting dictionary to JSON format as well. To convert a dictionary to JSON format, we will use the JSON module .dumps() method to handle this as shown below: 1#import json module 2import json 3#our dictionary 4user_dict = {‘name’: ‘Todd’, 5’age’: 28, 6’married’: None 7} 8#use the dumps method to change the dictionary back to json 9user_json = json.dumps(user_dict) 10#print our result 11print(user_json) 12# Output: {“name”: “Todd”, “age”: 28, “married”: null} 13   How to Read a JSON File We all must have had a struggle reading a JSON file that possibly might not return what we desired. Now, we’ll demonstrate an example of reading a JSON file in Python by using the .load() method. How to Write JSON to a file What we need to do is finally test how we can write out our JSON data into any file. We’ll demonstrate that by writing JSON data to a text format with the example code below. 1#import json module 2import json 3#the user details 4user_dict = {‘name’: ‘Todd’, 5’age’: 28, 6’married’: None 7} 8#we open an empty user.txt file here before we begin to dump the data 9with open(‘user.txt’, ‘w’) as json_file: 10 json.dump(user_dict, json_file) Pretty Print Our JSON Data We can also pretty print our JSON data to give it an appropriate structure, indenting, whitespace, and makes it look neater than the original form. An example of how we can implement this is shown below: 1import json 2 3user_data = ‘{“member”: “registered”, “status”: [“paid”, “active”]}’ 4 5# Getting dictionary 6user_dict = json.loads(user_data) 7 8# Pretty Print the user dict data 9print(json.dumps(user_dict, indent = 4, sort_keys=True))   If you found this post helpful, let us know in the comments box.

Blogs

How to Connect Python with SQL Database

In this tutorial, we will learn how to connect Python with SQL Database. Python is a programming language that allows users to work quickly and integrate systems more effectively while MySQL is the most popular Open Source Relational SQL database management system used for developing web-based software applications. We need to know that Python can be used in database applications and it is also very efficient. Let’s jump right in. How to Get Started We need to have MySQL installed on our computer before we dive in. You can download MySQL database at their Official WebsiteMySQL :: MySQL Downloads here. We also need to create a connection between MySQL and Python, the mysql.connector module can be used to handle this. To install mysql.connector, use the Pip module to install it by running the command below; pip install mysql-connector-python Connect to Database Now, we need to provide our credentials and connect to the database by using the code below. 1# import the connector here 2import mysql.connector 3 4# initiate a connector object 5the_db = mysql.connector.connect( 6 host = “localhost”, 7 user = “yourusername”, 8 password = “yourpassword” 9) 10 11# Print the object 12print(the_db)   Create Database Here, we will create our database and further create tables, the cursor instance will be parsed in with the CREATE command in creating our database. 1#import the connector module 2import mysql.connector 3 4#create a connection 5the_db = mysql.connector.connect( 6 host = “localhost”, 7 user = “yourusername”, 8 password = “your_password” 9) 10 11#we then create an instance of cursor class to use in executing our CREATE command 12cursor = the_db.cursor() 13 14#we then use cursor exceute with CREATE DATABASE command to create database CNDRO 15cursor.execute(“CREATE DATABASE cndro”)   Create Tables We can create tables by specifying our columns and as well the data types pertaining to them before enclosing them with the Cursor Execute Command. 1#import the connector here 2import mysql.connector 3#we provide our connection object using our credentials which now include the database name 4 5mydb = mysql.connector.connect( 6 host = “localhost”, 7 user = “yourusername”, 8 password = “your_password”, 9 database = “cndro” 10) 11#the cursor instance was created here 12cursor = mydb.cursor() 13 14#we pass the cursor to create the table named Students 15cursor.execute(“CREATE TABLE students (Lastname VARCHAR(255), Firstname VARCHAR(255), Address VARCHAR(255) )”)   If you found this post helpful, let us know in the comments box.

Blogs

How to Create an EC2 Instance In AWS -A Step by Step Guide

How to Create an EC2 Instance In AWS -A Step by Step Guide In this tutorial, we’ll be demonstrating how we can create an EC2 Instance in AWS. Let’s discuss a little about what Amazon EC2 is. The Amazon EC2 comprises both Windows and Linux-based operating systems which allows businesses owners to run application programs in the Amazon Web Services (AWS) public cloud. With EC2, we can launch as many virtual servers as we want and this provides compute capacity for IT projects and cloud workloads. How to set up Amazon EC2 Instance Sign in The first thing we are to do is to sign in to our AWS Management Console. We will then search for EC2 on the search bar which is under services. Create Instance Now, we’ll see the EC2 dashboard as seen in the image above. Afterward, we will click on Instances, which is by the left and this opens a new page as seen below. We will then click on the launch instances drop-down and select Launch Instances. Choose AMI On selecting the Launch Instances, it opens up a new page, which is for selecting our desired Amazon Machine Image(AMI). We’ll select the Ubuntu Server in this tutorial. So, you click the select button whenever you locate the Ubuntu Server. Choose Instance Type What we need to do next is to select our instance type. What we will do here is to select the Free tier eligible option as displayed in the image below. Then, after selecting this option, we will click on the Next: Configure Instance Details button to move to the next page. Configure Instance Now, it opens up the Configure Instance Page. Here, we won’t make any changes to the default settings we see there, we will then move to the next page by clicking on Next: Add Storage button. Add Storage What we need to do here is to add storage. You can go with the default settings here or change it to your desired size. Then we select the Next: Add Tags Button. Add Tags Here, we’ll be adding a tag that helps us to manage our instances and images. Click on the add tag and provide a key and value inside each box. We can use Demokey as the key and as well supply mypass under the value respectively. We then click on Next: Configure Security Group button. Configure Security Groups What we need to do next before we finish the whole process is to configure the security group. To do this we provide rules as SSH and HTTP. We can also provide more rules as we want. We do that by clicking the Add Rule button. We’ll also be changing our HTTP source from custom to Anywhere, so our application can be accessible to all users. After, click on Review and Launch Button. Review the whole Process Now, we will review all the settings and configurations we’ve made so far before we then click on the Launch Button. After selecting the Launch button, an image pops up which asks us how we want to generate our Key-Pair. We will select create a new key pair option here and use the RSA format and also type in the key name as mykey and we then click on Download Key Pair Button. After that, we scroll down and click on Launch Instances Button Now, our Instance will be up and running!! Click on EC2 Dashboard to view your running Instance.

Blogs

How to Extract Text from Images in Python Using Pytesseract OCR

In this tutorial, we’ll show you how to convert text from images into a machine-readable format with the help of the Python Pytesseract module. The Pytesseract Module is a Python wrapper for the Google Tesseract library for OCR. We will be using this module to convert the words in an image to a string. Optical Character Recognition(OCR) has been seen as a field of research in pattern recognition, artificial intelligence, and computer vision. This technique of extracting text from images is generally carried out by data scientists, software engineers, and at different work environments, whereby we know it’s certain the image would contain text data. Installation To install the Pytesseract on our machine, we will need to download the package. In this tutorial, we will use the Windows Operating system. You can as well download it like this: Pytesseract pip install Pytesseract Pillow pip install pillow The library requires the tesseract.exe binary to be indicated when specifying the path. So, during our installation, we can copy the path and keep it for use in the code later. This path highlighted in the image will be used in our code.   Sample one We will convert this particular image below to text by using the pytesseract module: Code: #we first import our libraries here from PIL import Image from pytesseract import * #Here we specified the path to our tessseract installation pytesseract.tesseract_cmd = “C:\\Users\\CNDRO\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe” #This is the name of the image we have above image_path = “brush.png” # Opening the image & storing it in an image object img = Image.open(image_path) #Providing the location to pytesseract library #pytesseract.tesseract_cmd = pytesseract # we will use this particular function to extract the text from the image text = pytesseract.image_to_string(img) # We will display the result below print(text[:-1])   Output: Sample Two Let’s say we have an image that has a lot of text, we can as well use the pytesseract module to extract our text from the image. We will demonstrate it with the image below: Code: #we first import our libraries here from PIL import Image from pytesseract import * #Here we specified the path to our tessseract installation pytesseract.tesseract_cmd = “C:\\Users\\CNDRO\\AppData\\Local\\Programs\\Tesseract-OCR\\tesseract.exe” #This is the name of the image we have above image_path = “behind.png” # Opening the image & storing it in an image object img = Image.open(image_path) #Providing the location to pytesseract library #pytesseract.tesseract_cmd = pytesseract# we will use this particular function to extract the text from the image text = pytesseract.image_to_string(img) # We will display the result below print(text[:-1]) Output: Thanks for reading this post. If you found this post helpful, share, and follow us for more tutorial posts.

Blogs

Introduction to Paginated Reports in Power BI

  Paginated reports are defined as highly formatted, pixel-perfect output result, reformed for printing or used for PDF generation. They are called “paginated” because they are designed to suit well on multiple pages and as well display all the data in a table, even if the table spans multiple pages. This Paginated reports are also perfect for operational reports, like sales invoices, report cards e.t.c. This article will introduce you to Paginated reports in Power BI. Let’s jump right in. Requirements A user needs a Power BI Pro license to publish a report to the service. You need to create a workspace in Power BI services and assign a dedicated capacity for paginated reports. In a Premium Gen1 capacity, a Power BI admin must enable paginated reports in the Premium capacities section of the Power BI admin portal. Comparison between Power BI Reports and Paginated Report Paginated reports doesn’t possess built-in data models like Power BI reports. A paginated report contains various built-in chart options including table, matrix, gauge, maps, sparklines, and different other chart types The supremacy of paginated reports is their ability to print all the data in a table, no matter how extended it takes. Also, printing is easier in a paginated report for a table, for instance, when a user prints or exports to PDF, the paginated report can contain as many pages necessary to print every row in the table. The Use of Report Builder Paginated reports possess its own design tool; this design tool is known as the Power BI Report Builder. This tool has same functionality as the tools used for creating paginated reports for Power BI Report Server or SQL Server Reporting Services(SSRS).With the use of this report builder we can preview the report before publishing to the Microsoft Power BI service. Features of Power BI Report Builder Data Modification: A user can group, filter, and sort data for paginated reports when using the report builder. A user can as well add formulas to their reports. Report Modification: Power BI Report Builder allows users to update and customize the reports created with the SQL Server Data Tools (SSDT) Report Designer. Multiple Layouts: A user can as well create Paginated Reports for matrix reports, column-based data for summarized data, chart reports for graph-based data e.t.c. Reporting from Multiple Sources: It also allows users to create reports that draws relational and multidimensional data from various sources like SQL Server and Analysis Services, Power BI datasets, etc. Data Sources With a single paginated report we can have as many different data sources and this makes it differ from Power BI Reports Data Model. We can also create embedded data sources and datasets inside the paginated report. These are some of the data sources we can connect to: Power BI datasets Oracle Teradata Azure SQL Database and Azure Synapse Analytics (via Basic and OAuth) Azure Analysis Services (via SSO) SQL Server via a gateway We can also export paginated reports in any of this various formats such as; Excel / CSV, PDF, Word, HTML and MHTML, XML. Today’s article introduced you to the basic things you need to know to start using paginated reports. We hope you will begin to explore all its features. Comment down below your observations or questions while using paginated reports in Power BI. Thanks for reading.

Blogs

Debugging in Python with the PDB Module

The Pdb module(python debugger) comes built-in to the Python standard library. This module uses bdb(basic debugger functions) and cmd(support for line-oriented command interpreters) modules. The python debugger also works on command line which is a great advantage for debugging code on remote servers. The module is already installed when you install python. Therefore, we only need to import it into our code to use its functionality. The Pdb module supports the following; Setting breakpoints Stepping through code Source code listing Viewing stack traces How to Invoke the Python Debugger To establish debugging in our program, we first insert import pdb, pdb.set_trace() commands in our code. With python 3.7 or later versions, we can replace the set_trace() with the breakpoint() function rather. Wherever the breakpoint() or set_trace() command is placed, the execution stops there. To run our program, we can use the python IDLE or the Visual Studio Code editor. Using the command line, we can run the following command in terminal python -m pdb program.py Sample Program One In this program, we want to compute an addition of different variables, we have added pdb.set_trace() at various locations in our code to know where error might occur. On running the program, we will find out it stopped and printed e=0.1 which tells us that particular line in our code hasn’t been executed yet. Sample Program Two In this program, we implemented a recursion function and also added the pdb.set_trace() at two different locations where our code will stop while debugging and we can pass in our variable using the print command. We pass in the variable value here with the print keyword, which hereby prints the result. Going forward, we can also run various commands on the terminal such as the c (continue execution), q (quit the debugger/execution), n(step to next line within the same function),s (step to next line in this function or a called function). using the help command, it shows us all the available functions and command available. We can have access to variables executed in our program both local and global variables. There are different commands we can use to access this, such as printing all arguments of function defined and are still currently active. We can use (a), the p command can as well use for printing result.

Blogs

Python Datetime Module: All You Need to Know

Python datetime is a module to work with dates in python which consists of four main classes which are: date, timedelta, time, and datetimes. We’ll implement how each of these objects can be used in our code. The Date Class The object represents a date which is an attribute of the year, month and day in an idealized calendar, the current Gregorian calendar indefinitely extended in both directions whereby January 1 of year 1 is called day number 1, January 2 of year 1 is called day number 2, and so on. The constructor of this class is represented as class datetime.date(year, month, day). For instance, we can have; from datetime import date # date object of today’s date today = date.today() print(“Current year:”, today.year) print(“Current month:”, today.month) print(“Current day:”, today.day)   The TimeDelta Class Python timedelta class is used for calculating differences in dates and times. This timedelta supports mathematical operations like additions, subtractions, multiplication, division etc. The constructor class for TimeDelta; class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Calculating difference between two date and times # Timedelta function demonstration from datetime import datetime, timedelta # Using current time current_time= datetime.now() # printing initial_date print(“date_now”, str(current_time)) # the other datetime result_date = current_time + \ timedelta(days=5) # printing new result_date print(“new_result_time”, str(result_date)) # printing calculated past_dates print(‘Time difference:’, str(result_date -current_time))   Different Operations supported by TimeDelta class Operator Description Addition (+) Adds and returns two timedelta objects Subtraction (-) Subtracts and returns two timedelta objects Multiplication (*) Multiplies timedelta object with float or int Division (/) Divides the timedelta object with float or int Floor division (//) Divides the timedelta object with float or int and return the int Modulo (%) Divides two timedelta object and returns the remainder +(timedelta) Returns the same timedelta object -(timedelta) Returns the resultant of -1*timedelta   The Time Class The time class of python datetime module represents a time quantity. The time class usually contain a tzinfo representing the timezone for which the time is specified. We must note that the date class doesn’t possess attributes related to time, also the time class doesn’t have date information, it’s only the dateclass that has both attributes pertaining to date and time. The constructor class for Time is; class datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) An example of how we can represent time by calling the time constructor is shown below. Representation of Time and obtaining hours, minutes, seconds, and microseconds from datetime import time # calling the constructor my_time = time(13, 24, 56) print(“Entered time”, my_time) # call the constructor with just one argument my_time = time(minute=12) print(“result with one argument”, my_time) # Calling constructor with no argument my_time = time() print(“Time with no argument”, my_time) Time = time(20, 25, 50) print(“hour =”, Time.hour) print(“minute =”, Time.minute) print(“second =”, Time.second) print(“microsecond =”, Time.microsecond)   The DateTime Class The DateTime class contains information on both date and time. The constructor class for the datetime class is ; class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)  Note: The year, month and day are very mandatory. The tzinfo can be set as None while the other attributes must be an integer. Representation of the Datetime class, get year, month, hour, minute, and timestamp # A program to demonstrate datetime object from datetime import datetime # call the constructor one = datetime(2001, 10, 12) print(one) # call the constructor with time parameters as well two = datetime(2001, 12, 10, 12, 12, 12, 212390) print(two) #call the year, month, hour, minute, timestamp a = datetime(2001, 12, 10, 12, 12, 12) print(“year =”, a.year) print(“month =”, a.month) print(“hour =”, a.hour) print(“minute =”, a.minute) print(“timestamp =”, a.timestamp())   We have the following Date class methods which we can use, you can check the documentation to get more. Function Name Description now() Returns current local date and time with tz parameter replace() Changes the specific attributes of the DateTime object strftime() Returns a string representation of the DateTime object with the given format strptime() Returns a DateTime object corresponding to the date string time() Return the Time class object timetuple() Returns an object of type time.struct_time timetz() Return the Time class object today() Return local DateTime with tzinfo as None   Converting DateTime to Strings We also need to convert our datetime to strings which can be for different reason. To convert datetime to strings, we will use the datetime.strftime and datetime.isoformat methods. Using ISO Format >>dt = datetime.now() >>print([dt.isoformat()]) [‘2022-03-16T16:23:21.505760’] Using the String Format time Method (.strftime format) >>> print(dt.strftime(‘Today is %Y, %B %d’)) Today is 2022, March 16 >>> print(dt.strftime(‘Date: %d/%m/%Y Time: %H:%M:%S’)) Date: 16/03/2022 Time: 16:28:54 These dates are usually in the form YYYY-MM-DD T HH:MM:SS.Microseconds The following are time format codes in Python which we can explore: %Y: the year in 4 digits %y: the year in 2 digits %m: month in 2 digits %B: full name of the month %w: week number from 0 to 6 %A: full name of the weekday %a: first three letters for the weekday %W: returns the week number of the year %d: day of the month %j: day of the year %H: hour %M: minute

Blogs

How to use KPI Visuals in Power BI

A Key Performance Indicator (KPI) is a visual cue that communicates the amount of progress made toward a measurable goal or shows how effectively you’re meeting your goals. KPI visual is a functional and effective visualization in Power BI. KPI Elements in Power BI Key Performance Indicators can be broken into three parts; Base value, Target value, and Status thresholds. Base value: a base value is a calculated field that usually results in a value or result, for example, it can be an aggregate of profit or sales for a specific period of time. Target value: The target value is a measure which is the goal all the rows should achieve. E.g. Sales target for all the salespersons. For instance, we can set a target value for entire units to be sold in a month as 500. Now, our base value will be the recorded value for a month. It can be less than 500, equal to 500, or greater than 500. Status thresholds: The status thresholds provide a rank to evaluate the base value and target values. The visual also presents a high and low threshold between which the base and target values fall to help users determine the status of the base value to the target value. Note: A KPI dataset also needs to contain goal values for a KPI. If your dataset doesn’t contain goal values, you can create them by adding an Excel sheet with goals to your data model or PBIX file How to Create a KPI in Power BI Desktop Open your report editor in Power BI Desktop then select a report on which you are working. On your right, you will see your Visualization pane and Fields pane. Navigate the Visualizations pane and select the KPI visual. After you’ve selected the KPI visual, three blank spaces are present in the Fields section; Indicator, Trend axis, and Target measure. We will go back to the Fields pane and find out all our data has been brought in. Select the field values (from table TotalSalesThisYear) and put them into the Indicator column. Then we will put the field FiscalMonth in the Trend axis column and the Goals field into the Target measure column. From the image below, this represents a sample KPI we’ll generate. We’ll go further to format the KPI by selecting the paint roller icon i.e. the Format section. Under here we can set the properties of our indicator, goal, trend axis, etc. After we’re done formatting the KPI to our desired output, we’ll generate a sample KPI that looks like what we have in the image below. KPI Custom Visualizations The KPI we created now is known as the Built-in KPI which comes with our Power BI Desktop. In addition to this built-in KPI, we have several other KPI-related visualizations that we can download from the Power BI Marketplace. To add custom KPI visualizations from the marketplace, we click on From Marketplace icon. From the Power BI Visuals dialog box, we have all the different types of available add-in visualizations to use. To view these related visuals, go to KPIs option and select from the list of visuals like Bullet Chart, Dual KPI, Power KPI, etc. KPI best practices There are different KPI best practices that we can observe to help us explore more on KPI usage. These tips are; You must only pick KPIs that are aligned to your specific goals. If your objectives aren’t clear, matching KPIs against them will prove complicated. Ensure you use different KPIs for the same goals if they stretch across groups. Ensure that whatever KPI you selected, there’s a core team responsible for defining them.

Scroll to Top