Example for pandas Code & Syntax in Python (2 Examples)

In this article you’ll learn how to use the functions of the pandas library in the Python programming language.

Preparing the Examples

import pandas as pd                                # Load pandas library
my_df = pd.DataFrame({"A":range(1, 10),            # Construct pandas DataFrame in Python
                     "B":["a", "x", "b", "y", "y", "c", "y", "d", "x"],
                     "C":range(11, 20),
                     "D":range(10, 1, - 1)})
print(my_df)
#    A  B   C   D
# 0  1  a  11  10
# 1  2  x  12   9
# 2  3  b  13   8
# 3  4  y  14   7
# 4  5  y  15   6
# 5  6  c  16   5
# 6  7  y  17   4
# 7  8  d  18   3
# 8  9  x  19   2

Example 1: Adding a New Variable to a pandas DataFrame in Python

E = ["d", "x", "h", "a", "y", "d", "a", "f", "d"]  # Create new column
print(E)
# ['d', 'x', 'h', 'a', 'y', 'd', 'a', 'f', 'd']
my_df1 = my_df.assign(E = E)                       # Appending list to DataFrame
print(my_df1)
#    A  B   C   D  E
# 0  1  a  11  10  d
# 1  2  x  12   9  x
# 2  3  b  13   8  h
# 3  4  y  14   7  a
# 4  5  y  15   6  y
# 5  6  c  16   5  d
# 6  7  y  17   4  a
# 7  8  d  18   3  f
# 8  9  x  19   2  d

Example 2: Calculating the Mean of a pandas DataFrame Variable in Python

my_df_mean = my_df["C"].mean()                     # Calculate mean of column
print(my_df_mean)
# 15.0

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top