Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
📊 Unit 1 – DataFrame  ·  Lesson 09

DataFrame: Create & Attributes

What is a DataFrame?

A DataFrame is a two-dimensional labelled table – like a sheet in Excel or a table in MySQL. It has a row index and column labels, and each column can hold a different data type.

df
NameMathsIP
0Asha7888
1Ravi9281
2Neha6595
3Om8874
Row index on the left · column labels on top · each column (highlighted) is a Series

Empty DataFrame

Python
import pandas as pd
df = pd.DataFrame()                 # an empty DataFrame
print(df)
print('empty:', df.empty)
Empty DataFrame Columns: [] Index: [] empty: True

From a dictionary of lists

Python
import pandas as pd
result = {'Name': ['Asha', 'Ravi', 'Neha', 'Om'],
          'Maths': [78, 92, 65, 88],
          'IP': [88, 81, 95, 74]}
df = pd.DataFrame(result)           # keys -> columns
print(df)
Name Maths IP 0 Asha 78 88 1 Ravi 92 81 2 Neha 65 95 3 Om 88 74

From a list of dictionaries

Python
import pandas as pd
rows = [{'City': 'Delhi', 'Temp': 31}, {'City': 'Pune', 'Temp': 27},
        {'City': 'Leh', 'Temp': 12, 'Snow': 'Yes'}]
df = pd.DataFrame(rows)             # each dict is one ROW
print(df)
City Temp Snow 0 Delhi 31 NaN 1 Pune 27 NaN 2 Leh 12 Yes

From a list of lists

Python
import pandas as pd
data = [[101, 'Pen', 10], [102, 'Pencil', 5], [103, 'Eraser', 3]]
df = pd.DataFrame(data, columns=['Code', 'Item', 'Price'], index=['a', 'b', 'c'])
print(df)
Code Item Price a 101 Pen 10 b 102 Pencil 5 c 103 Eraser 3

From Series

Python
import pandas as pd
maths = pd.Series([78, 92, 65], index=['Asha', 'Ravi', 'Neha'])
ip = pd.Series([88, 81, 95], index=['Asha', 'Ravi', 'Neha'])
df = pd.DataFrame({'Maths': maths, 'IP': ip})   # dictionary of Series
print(df)
Maths IP Asha 78 88 Ravi 92 81 Neha 65 95

From a NumPy array

Python
import pandas as pd
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
df = pd.DataFrame(arr, columns=['A', 'B', 'C'])
print(df)
A B C 0 1 2 3 1 4 5 6

Attributes

AttributeGives
indexRow labels
columnsColumn labels
dtypesData type of each column
valuesData as a NumPy array
shape(rows, columns)
sizerows × columns
ndimNumber of dimensions (2)
TTranspose
emptyTrue if no data
Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74],
                   'Grade': ['B', 'A', 'B', 'A']},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print('index  :', df.index.tolist())
print('columns:', df.columns.tolist())
print('shape  :', df.shape, '| size:', df.size, '| ndim:', df.ndim)
print(df.dtypes)
print(df.T)                         # transpose: rows <-> columns
index : ['Asha', 'Ravi', 'Neha', 'Om'] columns: ['Maths', 'IP', 'Grade'] shape : (4, 3) | size: 12 | ndim: 2 Maths int64 IP int64 Grade object dtype: object Asha Ravi Neha Om Maths 78 92 65 88 IP 88 81 95 74 Grade B A B A
Python
import pandas as pd
df = pd.DataFrame({'Maths': [78, 92, 65, 88], 'IP': [88, 81, 95, 74]},
                  index=['Asha', 'Ravi', 'Neha', 'Om'])
print(df.values)
print(df.head(2))
print(df.tail(1))
[[78 88] [92 81] [65 95] [88 74]] Maths IP Asha 78 88 Ravi 92 81 Maths IP Om 88 74

Summary

📘
dict of listskeys → columns
📗
list of dictseach dict → a row
📙
list of listseach inner list → a row; give columns=
📕
dict of SeriesSeries index → row index
Ways to create a DataFrame

Frequently Asked Questions

In a dictionary of lists, do keys become rows or columns?
Columns. Each key is a column name and its list is the column data.
What does shape return?
A tuple (rows, columns). A DataFrame with 4 rows and 3 columns has shape (4, 3) and size 12.
What happens if one dictionary in a list has an extra key?
A new column is created for that key and the other rows get NaN in it.
← Class 12 Informatics Practices
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDataFrame: loc, iloc, Add & Delete Your progress: 9 / 25 (36%) · Lesson 10 / 25 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free