Pandas DataFrame Methods equals(), filter(), first(), last(), head(), and tail()

https://blog.finxter.com/wp-content/uploads/2022/01/image-6.png

The Pandas DataFrame has several Re-indexing/Selection/Label Manipulations methods. When applied to a DataFrame, these methods evaluate, modify the elements and return the results.

This is Part 7 of the DataFrame methods series:

  • Part 1 focuses on the DataFrame methods abs(), all(), any(), clip(), corr(), and corrwith().
  • Part 2 focuses on the DataFrame methods count(), cov(), cummax(), cummin(), cumprod(), cumsum().
  • Part 3 focuses on the DataFrame methods describe(), diff(), eval(), kurtosis().
  • Part 4 focuses on the DataFrame methods mad(), min(), max(), mean(), median(), and mode().
  • Part 5 focuses on the DataFrame methods pct_change(), quantile(), rank(), round(), prod(), and product().
  • Part 6 focuses on the DataFrame methods add_prefix(), add_suffix(), and align().
  • Part 7 focuses on the DataFrame methods at_time(), between_time(), drop(), drop_duplicates() and duplicated().
  • Part 8 focuses on the DataFrame methods equals(), filter(), first(), last(), head(), and tail()

Getting Started

💡 Note: To follow along with the examples below, click here to download the finxters.csv file of auto-generated dummy user data. Move this file to the current working directory.

Remember to add the Required Starter Code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

Required Starter Code

import pandas as pd

Before any data manipulation can occur, this library will require installation:

  • The pandas library enables access to/from a DataFrame.

To install these libraries, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install pandas

Hit the <Enter> key on the keyboard to start the installation process.

Feel free to check out the correct ways of installing the library here:

If the installations were successful, a message displays in the terminal indicating the same.

DataFrame equals()

The equals() method compares two (2) DataFrames/Series against each other to determine if they have an identical shape and elements. If identical return True, otherwise return False.

The syntax for this method is as follows:

DataFrame.equals(other)
Parameter Description
other A DataFrame or Series to compare.

For this example, we have two (2) DataFrames containing grades for three (3) students.

df_scores1 = pd.DataFrame({'Micah': [91, 58, 73],
                           'Bob':     [53, 87, 46],
                           'Chloe':  [60, 54, 61]})
  
df_scores2 = pd.DataFrame({'Micah': [91, 58, 73],
                           'Bob':     [53, 87, 46],
                           'Chloe':  [60, 54, 61]})
  
result = df_scores1.equals(df_scores2)
print(result)
print(df_scores1.shape)
print(df_scores2.shape)
  • Line [1-2] creates two (2) DataFrames.
  • Line [3] compares df_scores1 against df_scores2 testing the shape and elements. The outcome saves to result (True/False).
  • Line [4] outputs the result to the terminal.
  • Line [5-6] confirms the shape of the DataFrames is equal by outputting the results to the terminal.

Output:

True
(3, 3)
(3, 3)

DataFrame filter()

The filter() method returns a subset of a DataFrame/Series rows/columns based on index label(s). This method does not filter a DataFrame/Series on the contents. The filter applies to the specific label(s) of the selected index. The return value is a subset of the callable.

The syntax for this method is as follows:

DataFrame.filter(items=None, like=None, regex=None, axis=None)
Parameter Description
items A filter list of columns to include in the result.
like A filter string of columns (ex: like='FID') to include in the result.
regex A regex string to filter columns (ex: regex='e$') to include in the result.
axis If zero (0) or index is selected, apply to each column. Default is None. If one (1) is selected, apply to each row.

For this method, various scenarios below highlight its capabilities.

This example uses the items parameter to filter the DataFrame and return the result.

Code – Example 1:

df_fxs = pd.read_csv('finxters.csv')
result = df_fxs.filter(items=['Username', 'Rank'])
print(result.head())
  • Line [1] reads in the comma-separated CSV file and saves it to df_fxs.
  • Line [2] filters df_fxs to include only the columns matching the item labels (Username and Rank). These columns (and associated values) save to result.
  • Line [3] outputs the first five (5) rows (head()) to the terminal.

Output:

  Username Rank
0 wildone92            Authority
1 AmyP             Beginner
2 1998_pete      Basic Knowledge
3 TheCoder  Experienced Learner
4 AliceM Authority

This example uses the like parameter to filter the DataFrame and return the result.

Code – Example 2:

df_fxs = pd.read_csv('finxters.csv')
result = df_fxs.filter(like='FID', axis=1)
print(result.head())
  • Line [1] reads in the comma-separated CSV file and saves it to df_fxs.
  • Line [2] filters df_fxs to include only the columns matching the like label ('FID'). This column (and associated values) save to result.
  • Line [3] outputs the first five (5) rows (head()) to the terminal.

Output:

  FID
0 30022145
1 30022192
2 30022331
3 30022345
4 30022359

This example uses the regex parameter to filter the DataFrame and return the result.

Code – Example 3

df_fxs = pd.read_csv('finxters.csv')
result = df_fxs.filter(regex='e$', axis=1)
print(result.head())
  • Line [1] reads in the comma-separated CSV file and saves it to df_fxs.
  • Line [2] filters df_fxs to include only the columns matching the regex label (First_Name, Last_Name and Username). These columns (and associated values) save to result.
  • Line [3] outputs the first five (5) rows (head()) to the terminal.

Output:

  First_Name Last_Name Username
0 Steve   Hamilton  wildone92
1 Amy  Pullister       AmyP
2 Peter       Dunn  1998_pete
3 Marcus   Williams   TheCoder
4 Alice    Miller    AliceM

Note: Each column name in the output ends with the letter e.

DataFrame first()

The first() method retrieves and returns the first set number of rows (periods) based on the value entered. The index must be a date value to return the appropriate results.

The syntax for this method is as follows:

DataFrame.first(offset)
Parameter Description
offset This parameter is the date period of the data to display (ex: 1M, 2D).

For this example, the blood pressure for three (3) patients over a two (2) month period is retrieved.

r = pd.date_range('2021-01-01', periods=3, freq='1M')
df = pd.DataFrame({'Patient-1': [123, 120, 144], 
                   'Patient-2': [129, 125, 90],
                   'Patient-3': [101, 95,  124]},index=r)

result = df.first('1M')
print(result)
  • Line [1] sets up the following:
    • The date range start date ('2021-01-01').
    • The number of periods (3).
    • The frequency ('1M'). This statement equates to 1 Month.
  • Line [2] creates a DataFrame containing:
    • Three (3) patient names containing three (3) elements of data for each patient.
  • Line [3] saves the first month period to result.
  • Line [4] outputs the result to the terminal.

Output:

  Patient-1  Patient-2  Patient-3
2022-01-31        123        129        101
2022-02-28        120        125         95

💡 Note: The date range for the selected frequency references the last day of the month.

DataFrame last()

The last() method retrieves and returns the last set number of rows (periods) based on the value entered. The index must be a date value for this method to return the expected results.

The syntax for this method is as follows:

DataFrame.last(offset)
Parameter Description
offset This parameter is the date period of the data to display (ex: 1M, 2D).

For this example, the blood pressure for three (3) patients over a  two (2) month period is retrieved.

r = pd.date_range('2021-01-01', periods=3, freq='1M')
df = pd.DataFrame({'Patient-1': [123, 120, 144], 
                   'Patient-2': [129, 125, 90],
                   'Patient-3': [101, 95,  124]},index=r)

result = df.last('1M')
print(result)
  • Line [1] sets up the following:
    • The date range start date ('2021-01-01').
    • The number of periods (3).
    • The frequency ('1M'). This statement equates to 1 Month.
  • Line [2] creates a DataFrame containing:
    • Three (3) patient names containing three (3) elements of data for each patient.
  • Line [3] saves the output to result.
  • Line [4] outputs the result to the terminal.

Output:

  Patient-1  Patient-2  Patient-3
2022-03-31        144 90 125

💡 Note: The date range for the selected frequency references the last day of the month.

DataFrame head() and tail()

These methods display n numbers of records (top or bottom). These methods are useful when you are accessing large amounts of data.

If no parameter is entered, by default, five (5) rows display.

  • The head() method returns the top five (5) rows of the DataFrame.
  • The tail() method returns the bottom five (5) rows of the DataFrame

If a parameter is entered in one of the above methods, n number of rows (top/bottom) will display.

As you will note, the head() method was accessed many times during this article. Both methods are must-haves in your knowledge base.

The syntax for these methods is as follows:

DataFrame.head(n=5)
DataFrame.tail(n=5)
Parameter Description
n An integer value indicating the number of rows to display. By default, five (5) rows display.

For this example, the first five (5) records from the DataFrame and the last five (5) records (tail) from the same DataFrame display.

df_fxs = pd.read_csv('finxters.csv')
print(df_fxs.head())
print(df_fxs.tail())

Output:

Finxter

Performance tips for Laravel

https://madewithlove.com/static/6649432301f833e8feabf4984fd5d3ae/laravel-performance-1.jpgThis is a story from the trenches on how we optimized the performance of a Laravel application using Eloquent.Laravel News Links

AR 15 Upper: Build, Buy, Better

https://www.recoilweb.com/wp-content/uploads/2022/01/AR-15-upper-cover.jpg

AR 15 Upper Cover

AR 15 Upper CoverIf the name of the game is modularity, the AR-15 certainly stands on the podium of best examples. The split receiver makes swapping calibers as easy as pulling two pins and replacing the AR 15 upper, with each one retaining its own zero, so long as you don’t remove the optic. Budget, custom performance, and the fun of it drive… moreRecoil

Comic for January 09, 2022

https://assets.amuniversal.com/d5abc33036a5013a89b9005056a9545d

Thank you for voting.

Hmm. Something went wrong. We will take a look as soon as we can.

Dilbert Daily Strip

A tongue-in-cheek look at an Air Force veteran

http://img.youtube.com/vi/kzLUcP6eTqQ/0.jpg

 

Here’s what its creator terms "A Hastily Created Documentary on the A-10 Warthog".  I had to laugh.  It’s only about 3 minutes long, but it’s fun.

A few grunts of my acquaintance, who relied on the Warthog to pull their butts out of trouble in the sandbox over several tours, also laughed as they watched it.  I daresay even the A-10’s pilots will enjoy it.

Peter

Bayou Renaissance Man

How to Get Free Microsoft Office for Students

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2022/01/office-apps-unsplash_.jpeg

How to Get Free Microsoft Office for Students

If you’re a student, you might be eligible for a free Microsoft Office subscription. Here’s how to get it.

Microsoft Office is the most widely used suite of office tools. It includes a word processor, a spreadsheet program, a presentation program, and several other tools. The company also sells different plans designed for non-profit, business, or personal usage.

If you are a school administrator, teacher, or student, you might be eligible for a free Microsoft 365 subscription. The Microsoft Office student package is great for students on a budget, especially those who don’t want to or can’t pay the full price for the Office Suite.

What’s Included in the Microsoft 365 Student Subscription?

A free Office 365 subscription is a fantastic choice for students as it lets them collaborate on popular web apps like Word, Excel, and PowerPoint. The free Office subscription also gives users a 50 GB mailbox and access to Microsoft Teams to freely communicate with other classmates.

Students also get access to personal cloud storage with OneDrive (unlimited for five or more users, otherwise it’s 1TB per user), as well as access to Microsoft Sway for creating interactive reports and presentations.

Related: The Best Features of Microsoft Sway for Creating Interactive Reports and Presentation

There are three tiers that Microsoft offers, namely:

  • Office 365 A1
  • Office 365 A3
  • Office 365 A5

A1 is available for free, but A3 and A5 are paid options, costing $2.5 per user per month and $6 per user per month, respectively. A more detailed breakdown of the pricing structure is also available on Microsoft’s academic website.

MAKEUSEOF VIDEO OF THE DAY

How to Sign Up for the Free Microsoft 365 Student Subscription

Microsoft has made it incredibly easy for students to sign up for a free Office student subscription. All you have to do is to enter your valid school email address on their official Office 365 Education website, and it’ll tell you whether your school’s eligible for the program.

If your institution is eligible, access will be immediately granted.

Related: How to Use OneNote for School: Tips for Students and Teachers

What if Your Institution Is Ineligible?

If, in case, your school is not eligible, you will get an option to sign up for an automated verification process. The process is mostly instantaneous, but in some cases, might take up to 30 days for completion.

Once you have access to Microsoft Office as a student, you might want to check out a few planner templates designed for students to help you manage your assignments and life better.

15 Checklist, Schedule, and Planner Templates for Students

Planning templates for students can help keep track of classes and homework, making preparations for the school year a breeze.

Read Next

About The Author

Najam Ahmed
(28 Articles Published)

Najam Ahmed is an experienced content marketer and copywriter with a focus on SaaS offerings, startups, digital agencies, and ecommerce businesses. He’s worked closely with founders and digital marketers over the past eight years to produce articles, eBooks, newsletters, and guides. His interests include gaming, traveling, and reading.

More
From Najam Ahmed

Subscribe to our newsletter

Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!

Click here to subscribe

MUO – Feed

New Lava-Like Coating Can Stop Fires In Their Tracks

sciencehabit shares a report from Science.org: It takes a lot of science to stop a fire. To prevent homes and workplaces from going up in smoke, manufacturers have added flame retardants to plastic, wood, and steel building materials for decades. But such additives can be toxic, expensive, and sometimes ineffective. Now, researchers in Australia and China have come up with a new flame retardant that, when exposed to extreme heat, forms a ceramic layer akin to hardened lava, squelching the flames before they spread. "This is very good work," says David Schiraldi, a chemist at Case Western Reserve University, who has developed other flame retardants. He notes that the ceramic’s starting materials aren’t particularly expensive or toxic, making it more likely to see widespread use. "[This] could impact public safety in the long run."
[The researchers] used three components. First, they created a mixture of several metal oxide powders — including oxides of aluminum, silicon, calcium, and sodium. That mix begins to melt at about 350C (below the temperature of most flames), forming a glasslike sheet. Next, the researchers added tiny flakes of boron nitride, which flow easily and help fill any spaces between the metal oxides as the glass forms. Finally, they added a fire-retardant polymer, which they described in ACS Nano in 2021. The polymer acts as a binder to glue the rest of the mixture to whatever it’s coating. That mix dissolved in water into a milky-white solution, which they then sprayed on a variety of surfaces, including rigid foam insulation, wood, and steel. After it dried, they blasted each coated material for 30 seconds with an 1100C butane torch. In each case, the coating melted into a viscous liquid, covering the material in a continuous glassy sheet.
When heated by the torch, coating spewed out nonflammable gases, such as carbon dioxide. As it did, it became more dense and formed a uniform, noncombustible char layer, which blocked flames from spreading to the materials underneath. The novel flame retardant protected rigid polymer foam — the kind used to insulate homes — better than more than a dozen commonly used retardants, the researchers report today in Matter. The new coating also excelled at protecting wood and steel. If sprayed on building materials during construction, the new coating could prevent disasters like the 2017 Grenfell Tower fire in London, where 72 people died, the researchers say.


Read more of this story at Slashdot.

Slashdot

Linux Kodachi: Extreme Privacy Protection Out of the Box

https://static1.makeuseofimages.com/wordpress/wp-content/uploads/2022/01/kodachi-linux.jpg

Privacy is one of the main reasons many people switch to Linux from Windows. For new Linux users, though, the learning curve involved with configuring a Linux system prevents them from fully achieving the privacy protection they want.

There is one Linux distribution, however, that delivers extreme security and privacy protection out of the box—even if you’ve never used Linux before. With Linux Kodachi, you’re protected automatically from the moment the system boots.

What Is Linux Kodachi?

Linux Kodachi is a live Debian-based Linux distribution that you can run directly from a USB drive on virtually any computer. It is similar to the TAILS Linux distribution but with some added layers of security and an easier setup for Linux beginners.

When used as suggested by the distribution’s developers, Linux Kodachi allows you to create a secure environment that makes it virtually impossible for anyone online to identify or track you as you go about your business.

On top of encrypting and anonymizing all internet connections, the system comes with some of the most advanced security and privacy tools already installed and ready to go. Kodachi even includes an emergency self-destruct button that will destroy the entire system along with any data it may contain.

In addition to protecting you while you work, the system also covers your tracks when you’re done. When you shut down the live system, all evidence of anything you did during your sessions vanishes, leaving the host computer untouched.

MAKEUSEOF VIDEO OF THE DAY

How to Install Linux Kodachi

Since Linux Kodachi is a live Linux distribution, you can boot it directly from a USB, DVD, or SD card. You can also boot and use it through virtualization software such as VMware, VirtualBox, or GNOME Boxes.

You can find all of the latest information about Kodachi along with download links for the most recent release at Eagle Eye Digital Solutions. There is a lot of information on the page that can be somewhat confusing at first glance (but well worth reading).

Download: Linux Kodachi

Once downloaded, you’ll need to create a bootable USB drive from the ISO image using a program such as Etcher. Then, of course, you’ll need to reboot your computer using the live Linux Kodachi USB.

When the live USB boots, the boot screen will have several options you can choose from. The easiest way to use Kodachi is to simply select the first live option: kodachi Legacy Live.

This will provide you with a fully functional and protected live system that leaves no trace of your session on the host computer. For a full explanation of the other boot options, you should refer to the Linux Kodachi website.

It will take a few moments for Kodachi to set itself up and then you’ll be presented with a heavily customized version of the XFCE desktop.

The desktop continuously displays a long list of details about your computer and internet connections organized into three columns on the right side of the screen.

The first column shows the status of hardware, such as processor and RAM usage. The second column displays mostly security information such as VPN and Tor status, encryption, and firewall settings.

The last column shows Linux system information such as kernel version and system uptime along with detailed network traffic information.

Kodachi comes with a wealth of privacy and security tools installed. Many of them activate automatically when the system boots. By default, with no intervention from you, the live system enables three major privacy and security-enhancing features:

  • Automatic connection to a VPN (all network traffic)
  • Automatic connection to the Tor network (browser traffic)
  • Automatic DNS encryption

This provides multiple layers of communication encryption out of the box. For those who want more, there is a wide variety of additional options that you can enable with the click of a button.

The Kodachi dashboard shows detailed security information about your current session along with a long list of configuration options. You can change how the system handles internet connections as well as which services and providers make up those connections.

At the time of writing, you can choose from configurations for:

  • Nine different VPN services plus the ability to add your own
  • 36 different Tor routing options
  • 23 different secured and unsecured DNS options

Linux Kodachi Software and Applications

Kodachi comes with a fully equipped toolbox of applications designed to allow you to do just about anything you want with your computer while maintaining your privacy and security.

There is a full system menu accessible from the left panel, but you’ll find most of the applications you probably want to use in folders attached to the dock at the bottom of your screen.

Among the pre-installed software, you will find several different browsers including Firefox, Tor Browser, and a few variants modified for extra security. You’ll also find an ample selection of security-oriented applications such as KeePass, OnionShare, Exif Cleaner, BleachBit, and more.

Using Kodachi With Persistent Storage

The Linux Kodachi system is fully functional when running as a live system from the USB. You can, however, create a live USB drive with persistent storage or install the operating system on the hard drive of your computer.

Installing Kodachi on your hard drive is as easy as clicking on the Install_Kodachi_Offline icon that appears on the live system’s desktop. For advanced users who want to create a bootable USB drive with persistent storage, we recommend following the instructions on the developer’s website.

Special Considerations When Using Persistent Storage

To maintain the highest level of security when installing Linux Kodachi on a hard drive, you should enable full disk encryption when the installer gives you the option.

With this option enabled, you will need to enter a password before the system boots. Without the password, the system will not load and the data on the hard drive will be unreadable.

With disk encryption enabled, you can then enable System Nuke after installation completes. This process will create a second boot password which will “nuke” the system if you enter it. When this process is triggered, encryption headers are instantly removed from the hard drive making it impossible to decrypt the data on it.

So, for example, if someone forces you to enter your password or give it to them so that they can enter it, using the special nuke password will instantly leave the entire contents of the hard drive in a permanently encrypted state.

A Warning About Users and Passwords

If you’ve installed Kodachi with persistent storage, it is a good idea to disable the automatic login function (you can do it through the Kodachi dashboard) and set a unique password for both the regular and root user accounts.

The default user account is kodachi (all lowercase) and the password for both the user account and the root account is r@@t00 (the last two digits are zeros).

Because Kodachi depends heavily on custom shell scripts, most of the functionality of the system will not work correctly if you log in under any account other than the default kodachi. You can change the passwords as you see fit, but you should not delete the kodachi user or log into the system under another user name.

Now You’re Ready to Explore the Web Anonymously

With Linux Kodachi running, you’re ready to use and explore the internet anonymously. Using the provided specialized browsers on top of the system’s base security and privacy protection, it will be virtually impossible for anyone to identify you as you move across the internet or deep web.

You can do everything you need to do (even browse dark web websites) with the confidence that you won’t be tracked.

The Best Dark Web Websites You Won’t Find on Google

The dark web isn’t for everyone, but some of it is worth exploring. Here are the best dark web websites worth checking out.

Read Next

About The Author

JT McGinty
(13 Articles Published)

JT is a tech industry veteran with more than 25 years of experience. From tech support to programming and system administration, he has done it all. He particularly enjoys teaching new users the freedom and power of Linux.

More
From JT McGinty

Subscribe to our newsletter

Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!

Click here to subscribe

MUO – Feed