pandas in one sentence#
pandas gives Python an Excel-like table (the DataFrame) with powerful tools to load, clean, analyse and export data - for files with thousands or millions of rows.
import pandas as pd # standard alias
Series - one column#
A Series is a one-dimensional labelled array (a single column with an index):
DataFrame - a table#
A DataFrame is a 2D table: rows (with an index) and named columns. Each column is a Series.
pandas में दो मुख्य चीज़ें हैं:
- Series = एक column (जैसे सिर्फ sales वाला column), जिसके साथ labels (index) होते हैं।
- DataFrame = पूरी table (कई columns), बिल्कुल Excel sheet जैसी।
DataFrame का हर column असल में एक Series है। Rows की पहचान index से होती है (default 0, 1, 2...)।
Selecting columns#
df["sales"] # one column → Series
df[["city", "sales"]] # several columns → DataFrame (note the double brackets)
df.sales # attribute style - works if the name has no spaces
Selecting rows and cells: loc and iloc#
loc - by label |
iloc - by position |
|
|---|---|---|
| one row | df.loc[2] |
df.iloc[2] |
| one cell | df.loc[2, "city"] |
df.iloc[2, 0] |
| slice | df.loc[1:3, "city":"sales"] (end included) |
df.iloc[1:3, 0:3] (end excluded) |
| condition | df.loc[df["sales"] > 80000, ["city", "sales"]] |
- |
Setting a meaningful index#
Filtering rows#
Boolean masks work exactly like NumPy:
Adding, changing and removing columns#
Calculations on whole columns (df["a"] / df["b"]) are vectorised - never loop over rows with for to calculate a column. It's slower and harder to read.
Sorting#
df.sort_values("sales", ascending=False)
df.sort_values(["region", "sales"], ascending=[True, False])
df.nlargest(3, "sales") # top 3
Summary#
Series= one labelled column;DataFrame= a table of Series.- Select columns with
df["col"]/df[["a", "b"]]; rows/cells withloc(labels) andiloc(positions). - Filter with boolean masks,
isin, orquery. - Create columns with vectorised expressions and
np.where; rename, drop and sort easily.