A Pandas DataFrame for traders is a table of price data, with dates as rows and Open, High, Low, Close and Volume as columns, that you can select, filter and calculate on with one line of Python. In this tutorial you will download NSE stock data from Yahoo Finance into a DataFrame and learn the core operations every trading script uses: selecting columns and rows, filtering, adding and removing columns, and plotting.
Pandas is an open-source Python library that is widely used for data manipulation and analysis. One of the most popular features of Pandas is the DataFrame. It is a two-dimensional table-like data structure that allows you to store and manipulate data in a way that is similar to a spreadsheet.
In this tutorial, we will be learning how to retrieve the stock data in pandas dataframe format, dataframe structure, selecting columns, selecting rows, filtering data, adding a column, removing a column, retrieving current trading price & prev day close price, and visualizing data using a simple line chart.

A DataFrame consists of rows and columns, where each row represents a unique observation or record, and each column represents a variable or feature of that observation. You can think of a DataFrame as a spreadsheet, where each row is a record, and each column is a field.
In this tutorial, we will learn how to create and manipulate DataFrames using yfinance and plot using seaborn python library.
Key Takeaways
yf.download()returns a DataFrame with the date as the index and OHLCV prices as columns.- Use
df['Close']for a column,df.loc[]for rows by date anddf.iloc[]for rows by position. - Boolean filters such as
df[df['Close'] > 150]work like spreadsheet filters. - Zomato now trades as Eternal (ETERNAL.NS), and recent yfinance and pandas versions need small code changes, covered in the 2026 update below.
Prerequisites
Before we begin, you will need to have the following:
- Python is installed on your computer.
- Jupyter Notebook (VS code Editor or Google Colab or any other IDE installed).
- Basic knowledge of Python syntax.
Installing Libraries
use the pip command as shown below to install the python libraries
pip install pandas yfinance seaborn matplotlib
Importing Libraries
Before we create a DataFrame, we need to import the necessary libraries. We will be using Pandas, yfinance seaborn, and matplotlib.
import pandas as pd
import yfinance as yf
import seaborn as sns
import matplotlib.pyplot as plt
Creating a DataFrame
There are several ways to create a DataFrame. In this tutorial, In this tutorial, we will use yfinance to fetch stock historical data and create DataFrames.
Creating a DataFrame from yfinance seaborn
yfinance is a Python library that allows you to download financial data from Yahoo Finance. To create a DataFrame from yfinance , we can use the yf.download() function.
df = yf.download('ZOMATO.NS', start='2021-01-01', end='2023-02-25')
# Display the first 5 rows of the DataFrame
df.head()
Output

This will download the stock data for Zomato from Yahoo Finance and create a DataFrame.
2026 note: Zomato Ltd was renamed Eternal Ltd and has traded under the NSE symbol ETERNAL since 9 April 2025 (Angel One), so ZOMATO.NS no longer returns data from Yahoo Finance. Use ETERNAL.NS to rerun this tutorial. See the updated version at the end of this post for other changes in newer yfinance releases.
Viewing DataFrame
To view the entire DataFrame, you can use the df function.
df

This will display the entire DataFrame.
Selecting Columns
To select a specific column in the DataFrame, you can use the column name in square brackets.
# Select the 'close' column
df['Close']

Selecting Rows
To select a specific row in the DataFrame, you can use the head function.

Besides head(), you can pick rows by date label with loc or by position with iloc:
# First five rows and last three rows
df.head()
df.tail(3)
# A single row by date label
df.loc['2022-06-01']
# A range of rows by date
df.loc['2022-06-01':'2022-06-10']
# Rows by position: first row, and the last five rows
df.iloc[0]
df.iloc[-5:]
Since the index is a date, loc slicing with two dates returns every trading day in between, which is the easiest way to look at a specific week or month.
Filtering Data
To filter the data in the DataFrame, you can use boolean indexing.
# Filter the data where the 'Close' price is greater than 150
df[df['Close'] > 150]

This will filter the data where the ‘Close’ price is greater than 150.
Adding a Column
To add a new column to the DataFrame, you can use the square bracket notation to assign a new column name and the values for that column.
# Calculate the daily return and add it as a new column
df['Daily Return'] = df['Close'].pct_change()
# Display the first 5 rows of the DataFrame
df.head()

This will calculate the daily return and add it as a new column to the DataFrame.
Print Column Headers
To print the column headers use df.columns
print(df.columns)

Resetting the Index of the DataFrame
It seems that the ‘Date’ column is not present in your dataframe. This might be due to the fact that when we download data using the yf.download method, the date column is automatically set as the index of the dataframe.
To confirm this, you can check the index of your dataframe by running:
print(df.index)
This will print the index of the dataframe, which should include dates.
If you want to add a separate ‘Date’ column to your dataframe, you can reset the index of the dataframe using the reset_index() method:
df = df.reset_index()

Visualizing Data
To visualize data in the DataFrame, you can use the sns and plt functions. Ensure Date and Close is present in the column where Date column is used for plotting x-axis and the close column as the y-axis co-ordinates.
# Create a line plot of the 'Close' price
sns.lineplot(x='Date', y='Close', data=df)
plt.show()

Retrieving the Current Close and Previous Closing Value
To retrieve the current close and previous closing value from the dataframe, we can use the iloc function of pandas. The iloc function is used to select rows and columns from the dataframe by integer index positions.
Here’s an example code snippet:
# Retrieve the current close and previous closing value
current_close = df['Close'].iloc[-1]
previous_close = df['Close'].iloc[-2]
# Print the values
print("Current Close:", current_close)
print("Previous Close:", previous_close)
Output
Current Close: 54.45000076293945
Previous Close: 54.95000076293945
In this code, we are first selecting the ‘Close’ column from the dataframe using df['Close']. We then use the iloc function to select the last row (iloc[-1]) and second last row (iloc[-2]) from this column to get the current and previous closing values respectively. Finally, we print the values using the print() function.
Note that the iloc function uses 0-based indexing, so iloc[-1] refers to the last row, iloc[-2] refers to the second last row, and so on.
Alternatively, we can also use
stock = yf.Ticker("ZOMATO.NS")
#retrieve daily data
df = stock.history(period="max", interval="1d")
close = df.Close.round(2)
# Retrieve and print the current close and previous closing value and 5 day back close price
print("Current Price :",close[-1])
print("Previous day closing Price :",close[-2])
print("5 Day Back closing Price :",close[-6])
Output
Current Price : 54.45
Previous day closing Price : 54.95
5 Day Back closing Price : 51.8
In newer pandas versions, close[-1] on a date-indexed Series raises a KeyError because pandas no longer falls back to position for integer keys. Use close.iloc[-1], close.iloc[-2] and close.iloc[-6] instead.
Removing Columns
df.drop function is used to remove the dataframe columns. The first print statement will print all the columns of the dataframe, including the ‘Date’ column. The second print statement will print the remaining columns after removing columns 6 and 7 (i.e. ‘Dividends’ and ‘Stock Splits’).
#Retrive Infy Data
stock = yf.Ticker("INFY.NS")
#retrieve daily data
df = stock.history(period="max", interval="1d")
close = df.Close.round(2)
#reset the index
df = df.reset_index()
#print the columns
print(df.columns)
#remove the columns 6 & 7
df.drop(df.columns[[6,7]], axis=1, inplace=True)
#print the remaining columns
print(df.columns)

Updated Version (2026)
The code above was written for 2023 versions of yfinance and pandas. Three things have changed since then:
yf.download()now defaults toauto_adjust=Trueand returns multi-level column names (Price, Ticker), even for one symbol (yfinance documentation). Passauto_adjust=Falseto keep unadjusted prices andmulti_level_index=Falseto get flat column names likeClose.- Positional access with
series[-1]on a date index no longer works in pandas; use.iloc. - The ZOMATO.NS symbol is now ETERNAL.NS.
This version of the full workflow was tested in November 2026 with yfinance 1.8 and pandas 3.1. The current and previous close for the same 2021–2023 date range match the original output (54.45 and 54.95).
import pandas as pd
import yfinance as yf
import seaborn as sns
import matplotlib.pyplot as plt
# Zomato Ltd was renamed Eternal Ltd; the NSE symbol is now ETERNAL
# auto_adjust=False keeps raw OHLC prices (yfinance now adjusts by default)
# multi_level_index=False gives flat column names: Open, High, Low, Close, Volume
df = yf.download('ETERNAL.NS', start='2021-01-01', end='2023-02-25',
auto_adjust=False, multi_level_index=False)
print(df.head())
# Select a column and filter rows
print(df['Close'].head())
print(df[df['Close'] > 150].head())
# Add a daily return column
df['Daily Return'] = df['Close'].pct_change()
# Move the Date index into a column and plot
df = df.reset_index()
sns.lineplot(x='Date', y='Close', data=df)
plt.show()
# Current and previous close: always use .iloc for positions
current_close = df['Close'].iloc[-1]
previous_close = df['Close'].iloc[-2]
print("Current Close:", round(current_close, 2))
print("Previous Close:", round(previous_close, 2))
# Ticker.history() still returns Dividends and Stock Splits columns
infy = yf.Ticker("INFY.NS").history(period="max", interval="1d").reset_index()
print(infy.columns)
infy = infy.drop(columns=['Dividends', 'Stock Splits'])
print(infy.columns)
Common Mistakes with Pandas DataFrames
- KeyError: ‘Date’: the date is the index, not a column. Call
df.reset_index()first, as shown above. - Comparing a DataFrame to a number: with multi-level columns,
df['Close']is a one-column DataFrame, not a Series, so filters and plots behave differently. Flatten the columns withmulti_level_index=False. - Chained assignment: write
df.loc[mask, 'col'] = valuerather thandf[mask]['col'] = value, which may not change the original DataFrame. - Mixing adjusted and unadjusted prices: decide which you need. Backtests over long periods usually use adjusted prices; levels you compare with a broker chart are unadjusted.
Continue with Part 2 of this Pandas DataFrame tutorial, or apply these skills in our complete yfinance guide and a Nifty monthly returns heatmap with yfinance and Seaborn.
Frequently Asked Questions
What is a DataFrame in Pandas?
A DataFrame is a two-dimensional table with labelled rows and columns, similar to a spreadsheet. For stock data, each row is usually a date and each column a field such as Open, High, Low, Close or Volume.
How do I convert yfinance data to a Pandas DataFrame?
yf.download() already returns a Pandas DataFrame. Pass multi_level_index=False for flat column names, and call reset_index() if you want the date as a normal column.
What is the difference between loc and iloc in Pandas?
loc selects rows and columns by label, such as a date or column name. iloc selects by integer position, such as iloc[-1] for the last row.
Why does ZOMATO.NS not work in yfinance?
Zomato was renamed Eternal Ltd and its NSE symbol changed to ETERNAL in April 2025, so use ETERNAL.NS.
Learn by watching: free videos every week
Market Profile, order flow, Python, AI and OpenAlgo tutorials on YouTube.

