Pandas is a powerful Python library for data manipulation and analysis. It provides two main data structures: Series for one-dimensional data and DataFrame for tabular, two-dimensional data.
With Pandas you can easily load, clean, transform, and analyze structured data from sources like CSV, Excel, SQL databases, and more.
To use Pandas, you first install it with pip and then import it in your Python script, usually with the alias pd.
A Series can be created from a Python list, NumPy array, or dictionary. A DataFrame is often created from a dictionary of lists or from external data files (like CSV).
A Series stores a single column of data with an index. If you don't specify the index, Pandas creates a default integer index starting from 0.
A DataFrame is like a table: each column is a Series, and each row has an index. You can access columns by name and rows by label or integer position.
# Install pandas library
pip install pandas
import pandas as pd # Import the pandas library
data = [10, 20, 30, 40] # Define a list of numbers
series = pd.Series(data) # Create a Series from the list
print(series) # Display the Series
import pandas as pd # Import the pandas library
data = { # Dictionary to build the DataFrame
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data) # Create a DataFrame from the dictionary
print(df) # Display the DataFrame
# Access a single column
print(df["Name"])
# Access multiple columns
print(df[["Name", "Age"]])
# Access rows by label (index)
print(df.loc[0])
# Access rows by integer position
print(df.iloc[0])
If you run the Series example, the output will look like this:
0 10 1 20 2 30 3 40 dtype: int64
The left side (0, 1, 2, 3) is the index, and the right side is the value. dtype shows the data type of the values.
For the DataFrame example, the output will look like a table:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
Each row has an index (0, 1, 2) and each column (Name, Age, City) has its own label.
DataFrame for tabular data and Series for 1D data.loc for label-based indexing and iloc for integer-based indexing.df.dtypes before performing operations.copy() when needed to avoid unintentionally modifying original data.DataFrame for your favorite books and their authors.loc and iloc.Is_New = Year >= 2020).