Python Pandas Basic Usage

Importing Pandas:
Pandas is usually imported under the “pd” alias:
import pandas as pd
Creating a DataFrame:
data = {
    "Name": ["Alice", "Bob", "Charlie"],
    "Age": [25, 30, 35]
}

df = pd.DataFrame(data)
Accessing Data:
df[column_name]Single column
df[[column1, column2, ... ]]Multiple columns
df.loc[row_label]Row by row index label (row name)
df.loc[[label1, label2, ...]]Multiple rows by index label
df.iloc[row_number]Row by row number
df.iloc[[row1, row2, ...]]Multiple rows by row number
df[start:stop:step]Rows based on slicing notation where start is the first row, stop is last row, and step is the number of rows to advance after each extraction.

Exhibit 25.54 Commands to retrieve data from DataFrames.

Commands to retrieve data from DataFrames are listed in Exhibit 25.54, and their use is illustrated in the below code:

# Access a specific column:
df["Name"]

# Access a specific row:
df.iloc[1] # Second row

# Access a specific cell:
df.at[1, "Age"] # Age, second row
Basic Operations:
# Add a new column:
df["City"] = ["New York", "Los Angeles", "Chicago"]

# Delete a column:
df.drop("City", axis=1, inplace=True)

# Filter rows based on a condition:
df[df["Age"] > 30]

# The shape property returns a tuple containing the number of rows and columns of the DataFrame:
df.shape # returns (2, 3)

Previous     Next

Use the Search Bar to find content on MarketingMind.