Sitemap
Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com

DataFrame for beginners using Python

--

Press enter or click to view image in full size

I know I struggled with data frames and managing the time complexity when I had thousands of rows to manage and implement operations, so here is something for the beginners to look and practice to build some confidence.

Let’s start by understanding data frames, have you ever worked on Microsoft excel? If yes, then you may skip the part. If no, data frames is a two-dimensional array-like structure in which column contains the variables and each row contains one set of values. In the image below, col1, col2, col3 are the column variables.

Lets’s start by creating a DataFrame,

import pandas as pd
df1 = pd.DataFrame([[1, 4, 3], [4, 5, 6], [7, 8, 9]], columns = [‘col1’, ‘col2’, ‘col3’])

The above command will create a DataFrame and it would look like:

Now, let’s have two DataFrames,

DataFrame — df1
DataFrame — df2

While merging or adding rows to any of the DataFrame, first we need to forget about the loops. No, O(n) is not a good approach when it comes to DataFrames, we can work in O(1). This is where DFs comes in handy and saves us a lot of time.

Get shivam kalra’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s say we need to merge df1 and df2 based on a column — 1, first comes to a question, how we need to merge- left? right? inner? or outer? These are the types of joins if we do not mention it automatically detects inner join. The below command is shown with the inner join.

df1 = df1.merge(df2, left_on = ‘col1’, right_on = ‘col1’, how = ‘left’)

In ‘left_on’ and ‘right_on’, we mention the columns to consider for joining. Here we are joining based on the column- ‘col1’ and df1 is merged with df2. Now, the DataFrame looks like

Press enter or click to view image in full size

Now if we did not want the columns of df2 to be included in df1, then code will look like-

df1 = df1.merge(df2['col1'], left_on = 'col1', right_on = 'col1', how = 'left')

By this, we can only see ‘col1’, ‘col2’ and ‘col3’. df2[‘col1’] we only included the ‘col1’ while merging. See the image below to see the difference.

There are times when you need to know which row is present in df1 or df2 or both. For this, we use an indicator, this helps us with an additional column which states ‘left_only’, ‘right_only’ or ‘both’-

df1 = df1.merge(df2['col1'], left_on = 'col1', right_on = 'col1', how = 'left', indicator = True)
DataFrame with an indicator

Now, if we need to drop, the rows where _merge = ‘left_only’, add a ‘query’ and drop — merge column.

df1 = df1.merge(df2['col1'], left_on = 'col1', right_on = 'col1', how = 'left', indicator = True).query("_merge == 'left_only'").drop('_merge',axis = 1)
Dropped merge with left_only

Now, this is the time I should tell you for each row an Index is maintained so if you are using anaconda you will be able to see it anyways, here are the images with the index.

Image1
Image2

Image2 is the image of the ‘dropped merge with ‘left_only’’. But, the index value is 3 instead of 0. The reason is, each row has a unique indexed value, so if you drop other rows the index value does not change. However, it is a good practice to reset the index after every merge operation. Follow the code snippet.

df1.reset_index(drop = True, inplace = True)

This is how it looks like, why did I use inplace = True? when we assign some task we have to save it to the variable, here we are using the same variable to assign the changes, it is similar to

df1 = df1.reset_index(drop = True)

Adding the column to the DataFrame, let’s consider the original df1(the first image).

df1['col4'] = ''

The new column named ‘col4’ is created with all the row values blank.

Drop a column, this comes in handy when you need to apply several tasks with one data frame. In the below code snippet I’ve used axis = 1 which says to search for the name in the columns.

df1.drop('col1', inplace = True, axis = 1)

Drop Duplicate values in rows, if we need to find duplicate values in particular columns then we use keyword — ‘subset’ otherwise don’t use it.

df1.drop_duplicates(subset = 'col1', inplace = True)

Returning the index values of the rows based on the conditions of particular columns. Sometimes we require index values and work with them after. Here is a code snippet for that-

index_values = df1[df1['col1'] == 1].index

In DataFrames ‘and’, ‘or’ these won’t work we have to use boolean, using ‘&’ and ‘|’ instead would work. Likewise, when we need to search values in an array we use ‘in’ but with DataFrames we use ‘isin’ keyword. See the code snippet.

array = [1,4,9]
1 in array
# This returns True but we cannot use this in DataFrames
df1['col1'].isin(array)
# 'col1' has values [1,4,7]
'''
This returns
0 True
1 True
2 False
'''

I hope, I covered the amount which would get you started on DataFrames, and build some confidence.

--

--

shivam kalra
shivam kalra

Written by shivam kalra

Writer || Software Developer || Always happy to share some valuable information.

Analytics Vidhya
Analytics Vidhya

Published in Analytics Vidhya

Analytics Vidhya is a community of Generative AI and Data Science professionals. We are building the next-gen data science ecosystem https://www.analyticsvidhya.com