Pandas Data Manipulation: Sorting, Selecting, Grouping, and Reshaping
This article provides a visual guide to using Pandas for data manipulation, covering sorting with sort_values, column selection, grouping with groupby and various aggregations, filtering rows and columns, dropping, joining, merging, pivot tables, melting, stacking, unstacking, and index operations, illustrated with code snippets and screenshots.
Pandas is a common tool for data mining; mastering its functions is essential. This guide demonstrates various Pandas operations through visual examples.
sort_values
(dogs[dogs['size'] == 'medium']
.sort_values('type')
.groupby('type').median())Execution steps:
Filter rows where the size column equals "medium".
Convert the type column as needed.
Group by type and compute the median.
selecting a column
dogs['longevity']groupby + mean
dogs.groupby('size').mean()Execution steps:
Group data by the size column.
Perform aggregation (mean) within each group.
grouping multiple columns
dogs.groupby(['type', 'size'])groupby + multi aggregation
(dogs
.sort_values('size')
.groupby('size')['height']
.agg(['sum', 'mean', 'std']))Execution steps:
Sort data by the size column.
Group by size.
Calculate sum, mean, and standard deviation of height within each group.
filtering for columns
df.loc[:, df.loc['two'] <= 20]filtering for rows
dogs.loc[(dogs['size'] == 'medium') & (dogs['longevity'] > 12), 'breed']dropping columns
dogs.drop(columns=['type'])joining
ppl.join(dogs)merging
ppl.merge(dogs, left_on='likes', right_on='breed', how='left')pivot table
dogs.pivot_table(index='size', columns='kids', values='price')melting
dogs.melt()pivoting
dogs.pivot(index='size', columns='kids')stacking column index
dogs.stack()unstacking row index
dogs.unstack()resetting index
dogs.reset_index()setting index
dogs.set_index('breed')The article concludes with a brief disclaimer and a call‑to‑action to read the original source.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
