Skip to content
Course Notes
Use this workspace to take notes, store code snippets, or build your own interactive cheatsheet! For courses that use data, the datasets will be available in the datasets
folder.
Pandas Dataframe
Creating DataFrames
import pandas as pd
- Create a dictionary with the exact column names holding the Apple data.
- Create a DataFrame using the dictionary.
# Create dict holding the data
data = {'Sym': ['APPL', 'APPL', 'APPL'],
'Price': [105.00, 117.05, 289.80],
'Date': ['2015/12/31', '2017/12/01', '2019/12/27']}
# Create DataFrame from the data
positions = pd.DataFrame(data=data)
print(positions)
- Create a list of dictionaries with the position data.
- Create a DataFrame using the list.
# Make list of dictionaries
data = [{'Sym': 'APPL', 'Price': 105.00, 'Date': '2015/12/31'},
{'Sym': 'APPL', 'Price': 117.05, 'Date': '2017/12/01'},
{'Sym': 'APPL', 'Price': 289.80, 'Date': '2019/12/27'}]
# Create DataFrame from the list
positions = pd.DataFrame(data=data)
print(positions)
- Create a list of lists representing the positions data.
- Define the column names.
- Create a DataFrame from the data.
# Create a list of lists
data = [['APPL', 105.00, '2015/12/31'],
['APPL', 117.05, '2017/12/01'],
['APPL', 289.80, '2019/12/27']]
# Define the column names
columns = ['Sym', 'Price', 'Date']
# Create a DataFrame with the data and column names
df = pd.DataFrame(data=data, columns=columns)
print(df)
Reading market history
# Read the data
stocks = pd.read_csv('datasets/HistoricalQuotes.csv')
# Look at the data
print(stocks)
Accessing Data
Introducing lesson data
import pandas as pd
data = [
['a', 'BA', 'ajfdk2', 1222.00],
['b', 'AAD', '1234nmk', 390789.11],
['c', 'BA', 'mm3d90', 13.02]
]
accounts = pd.DataFrame(data, columns=['', 'Bank Code', 'Account#', 'Balance'])
accounts = accounts.set_index('')
display(accounts)