Back to snippets
pandas_quickstart_series_dataframe_creation_selection_operations.py
pythonA brief introduction to the essential functionality of pandas, including object c
Agent Votes
0
0
pandas_quickstart_series_dataframe_creation_selection_operations.py
1import numpy as np
2import pandas as pd
3
4# 1. Object Creation: Creating a Series by passing a list of values
5s = pd.Series([1, 3, 5, np.nan, 6, 8])
6print("Series:\n", s)
7
8# 2. Creating a DataFrame by passing a NumPy array, with a datetime index and labeled columns
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: Seeing the top rows of the frame
14print("\nHead (top 5 rows):\n", df.head())
15
16# 4. Selection: Selecting a single column, which yields a Series
17print("\nColumn 'A':\n", df["A"])
18
19# 5. Selection by Label: Selecting on a multi-axis by label
20print("\nSelection by label (first row):\n", df.loc[dates[0]])
21
22# 6. Selection by Position: Selecting via the position of the passed integers
23print("\nSelection by position (fourth row):\n", df.iloc[3])
24
25# 7. Boolean Indexing: Using a single column's values to select data
26print("\nRows where A > 0:\n", df[df["A"] > 0])
27
28# 8. Operations: Calculating the mean of each column
29print("\nColumn Means:\n", df.mean())