DataFrames

In this section, we are going to learn about pandas DataFrames. DataFrames are two-dimensional labeled data structures that have columns and may be of different data types. DataFrames are similar to SQL tables or a spreadsheet. They are the most common object when working with pandas.

Now, we are going to look at an example of reading data from a csv file into a DataFrame. For that, you must have a csv file present in your system. If you don't have a csv file in your system, create a file named employee.csv, as follows:

Id, Name, Department, Country
101, John, Finance, US
102, Mary, HR, Australia
103, Geeta, IT, India
104, Rahul, Marketing, India
105, Tom, Sales, Russia

Now, we are going to read this csv file into a DataFrame. For that, create a script called read_csv_dataframe.py and write the following content in it:

import pandas as pd

file_name = 'employee.csv'
df = pd.read_csv(file_name)
print(df)
print()
print(df.head(3))
print()
print(df.tail(1))

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 read_csv_dataframe.py
Output:
Id Name Department Country
0 101 John Finance US
1 102 Mary HR Australia
2 103 Geeta IT India
3 104 Rahul Marketing India
4 105 Tom Sales Russia


Id Name Department Country
0 101 John Finance US
1 102 Mary HR Australia
2 103 Geeta IT India

Id Name Department Country
4 105 Tom Sales Russia

In the preceding example, we first created a csv file called employee.csv. We are using the pandas module to create data frames. The goal is to read that csv file into the DataFrame. Next, we created a df object and we are reading the contents of a csv file into it. Next we are printing a DataFrame. Here, we used the head() and tail() methods to get the particular number of lines of data. We specified head(3), which means we are printing the first three lines of data. We also specified tail(1), which means we are printing the last line of data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset