The Pandas DataFrame
What is a Pandas DataFrame?
| Case | Var a | Var b | … | Var i | … | Var k |
|---|---|---|---|---|---|---|
| 1 | a₁ | b₁ | … | i₁ | … | k₁ |
| 2 | a₂ | b₂ | … | i₂ | … | k₂ |
| j | aⱼ | bⱼ | … | iⱼ | … | kⱼ |
| n | aₙ | bₙ | … | iₙ | … | kₙ |
How do I create a DataFrame?
How do I pass an iterable to the DataFrame class?
| Routine | Synopsis |
|---|---|
pd.DataFrame.from_dict |
Construct DataFrame from dict of array-like or dicts |
pd.DataFrame.from_records |
Convert structured or record ndarray to DataFrame |
pd.DataFrame.sparse.from_spmatrix |
Create a new DataFrame from a SciPy sparse matrix (helpful for network data) |
Notes: the statements included in the ‘Routine’ column assume Pandas is loaded with the pd alias.
Can you show me .DataFrame.from_dict in action?
# import pandas with the socially accepted alias 'pd'
>>> import pandas as pd
# create a dictionary of arrays
>>> my_data = {
"var_1": [1, 2, 3, 4, 5],
"var_2": ["ABC", "Hello world", "Bazinga!", "cheers", "ciao"],
}
# get a DataFrame from the dictionary and display it
>>> df = pd.DataFrame.from_dict(my_data)
>>> df
var_1 var_2
0 1 ABC
1 2 Hello world
2 3 Bazinga!
3 4 cheers
4 5 ciao
# create a dictionary whose keys are cases
>>> my_data = {"case_1": ["Pluto", "dog"], "case_2": ["Goofy", "dog"]}
# get a DataFrame from the dictionary and display it
>>> df = pd.DataFrame.from_dict(my_data)
>>> df
case_1 case_2
0 Pluto Goofy
1 dog dog
# ... something wrong here - let us adjust the optional param 'orient'
>>> df = pd.DataFrame.from_dict(my_data, orient="index")
>>> df
0 1
case_1 Pluto dog
case_2 Goofy dog
# ... still something wrong here - where are the column names?
>>> df = pd.DataFrame.from_dict(
my_data, orient="index",
columns=["name", "species"]
)
>>> df
name species
case_1 Pluto dog
case_2 Goofy dogHow do I create a DataFrame from ‘external’ data?
# import pandas with the socially accepted alias 'pd'
>>> import pandas as pd
# create fake data and write them to a .csv
# --+ column names
>>> columns = ["x", "y"]
# --+ column values
>>> x = [0, 1, 2]
>>> y = ["A", "B", "C"]
# --+ write the data to a file
>>> with open("my_data.csv", "w") as f:
# write the column names first
f.write(",".join(columns) + "\n")
# then, write the data case-by-case
for i, j in zip(x, y):
f.write("{},{}".format(i, j) + "\n")
# --+ close the pipe
f.close()
# create a DataFrame from the .csv file and display it
>>> df = pd.read_csv("my_data.csv")
>>> df
x y
0 0 A
1 1 B
2 2 CFootnotes
In field of information systems and computer science, columns are often called fields; statisticians, economists, and analysts in general use the term variable to refer to a column; the term feature is common in the Machine Learning field.↩︎
throughout the book, I refer to Python sessions without loss of generality. The points I make are valid also for IPython or Jupyter sessions.↩︎