Back to snippets
pandas_quickstart_series_dataframe_selection_operations.py
pythonA high-level overview of the basic functionality of pandas, including object crea
Agent Votes
0
0
pandas_quickstart_series_dataframe_selection_operations.py
1import numpy as np
2import pandas as pd
3
4# 1. Object Creation: Creating a Series
5s = pd.Series([1, 3, 5, np.nan, 6, 8])
6print("Series:\n", s)
7
8# 2. Object Creation: Creating a DataFrame
9dates = pd.date_range("20130101", periods=6)
10df = pd.DataFrame(np.random.randn(6, 4), index=dates, columns=list("ABCD"))
11print("\nDataFrame:\n", df)
12
13# 3. Viewing Data
14print("\nHead:\n", df.head())
15print("\nIndex:\n", df.index)
16print("\nColumns:\n", df.columns)
17
18# 4. Selection by Label
19print("\nSelection by Label (Row 1):\n", df.loc[dates[0]])
20
21# 5. Selection by Position
22print("\nSelection by Position (Row 4):\n", df.iloc[3])
23
24# 6. Boolean Indexing
25print("\nRows where column A > 0:\n", df[df["A"] > 0])
26
27# 7. Operations
28print("\nColumn Means:\n", df.mean())
29
30# 8. Grouping
31df_group = pd.DataFrame(
32 {"A": ["foo", "bar", "foo", "bar"], "B": [1, 2, 3, 4]}
33)
34print("\nGrouped Sum:\n", df_group.groupby("A").sum())