0% found this document useful (0 votes)
22 views

Essential Python Commands

Important Python command sequences

Uploaded by

shehryarahmed2k
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Essential Python Commands

Important Python command sequences

Uploaded by

shehryarahmed2k
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Table 1: Essential Python Commands

Command Name Syntax Definition/Operation


print(object) Outputs the specified object to the
Print
console.
Assigns a value to a variable,
Variable variable_name = value allowing it to be referenced later in
Assignment
the code.
Yahoo Finance
Executes a block of code if the
If Statement if condition:
condition is True.
Executes a block of code if the
Else Statement else:
preceding if condition is False.
Adds an additional condition to an
Elif Statement elif condition: if statement, checked if the
previous conditions were False.
Iterates over items in an iterable
For Loop for variable in iterable: (like a list or range), executing a
block of code for each item.
Repeats a block of code as long as
While Loop while condition:
the condition is True.
Function def Defines a function, encapsulating a
Definition function_name(parameters): block of code to be reused.
Return return value Exits a function and optionally
Statement returns a value to the caller.
list_name = [item1, Creates a list, an ordered collection
List item2, ...] of items.
dict_name = {key1: Creates a dictionary, a collection of
Dictionary value1, ...} key-value pairs.
set_name = {item1, Creates a set, an unordered
Set item2, ...} collection of unique items.
tuple_name = (item1, item2, Creates a tuple, an ordered,
Tuple ...) immutable collection of items.
List [expression for item in A concise way to create a list based
Comprehension iterable] on existing iterables.
Returns the length (number of
Len len(object) items) of an object like a list, tuple,
or string.
range(start, stop, step) Generates a sequence of numbers,
Range
often used in loops.
import module_name Imports a module, allowing access
Import
to its functions and variables.
Class Definition class ClassName: Defines a class, a blueprint for
Command Name Syntax Definition/Operation
creating objects with attributes and
methods.
Handles exceptions (errors) that
Try-Except try: except Exception: occur in a block of code, allowing
Block
the program to continue running.
Opens a file, with mode specifying
File Open open(file_name, mode) the operation (e.g., 'r' for read,
'w' for write).
with open(file_name, mode) Simplifies file handling by
With Statement as file: automatically closing the file when
the block is exited.
Append to List list_name.append(item) Adds an item to the end of a list.
Remove from list_name.remove(item) Removes the first occurrence of an
List item from a list.
Extracts a portion of a list, string, or
Slice list_name[start:stop:step] tuple based on start, stop, and step
values.
Applies a function to every item in
map(function, iterable) an iterable (e.g., list), returning a
Map
map object (can be converted to a
list).
Filters items in an iterable based on
Filter filter(function, iterable) a function that returns True or
False.
lambda arguments: Creates an anonymous function,
Lambda expression often used for short, simple
functions.
sum(iterable) Returns the sum of all elements in
Sum
an iterable (e.g., list).
Returns the largest/smallest item in
Max/Min max(iterable) min(iterable) an iterable or among two or more
arguments.

Table 2: Essential Pandas Commands

Command
Syntax Definition/Operation
Name

Import import pandas as pd Imports the Pandas library,


Command
Syntax Definition/Operation
Name

commonly aliased as pd to simplify


Pandas
usage.

Reads a CSV file into a Pandas


Read CSV pd.read_csv(file_path) DataFrame, which is a table-like
structure for data.

Creates a DataFrame from data


DataFrame pd.DataFrame(data)
(e.g., a dictionary or list).

Returns the first n rows of the


Head df.head(n) DataFrame. Defaults to 5 rows if n
is not specified.

Returns the last n rows of the


Tail df.tail(n) DataFrame. Defaults to 5 rows if n
is not specified.

Provides summary statistics (mean,


Describe df.describe() std, min, max, etc.) for numerical
columns in the DataFrame.

Displays a concise summary of the


Info df.info() DataFrame, including data types
and non-null counts.

Accesses a single column in the


Indexing df['column_name']
DataFrame as a Series.

Accesses a group of rows and


Loc df.loc[row_label, col_label] columns by labels or boolean
arrays.

Accesses a group of rows and


Iloc df.iloc[row_index, col_index]
columns by integer positions.

Drops a specified column from the


Drop
df.drop('column_name', axis=1) DataFrame. Use axis=1 for
Column
columns and axis=0 for rows.

Drops a specified row by index


Drop Row df.drop(index)
label from the DataFrame.

Sort Values df.sort_values(by='column_name') Sorts the DataFrame by the values


Command
Syntax Definition/Operation
Name

of a specified column.

Rename df.rename(columns={'old_name': Renames specified columns in the


Columns 'new_name'}) DataFrame.

Filters rows in the DataFrame


Filter Rows df[df['column_name'] > value] where the column values satisfy a
condition.

Add New Adds a new column to the


df['new_column'] = data
Column DataFrame with the specified data.

Groups the DataFrame by a


specified column and performs an
Group By df.groupby('column_name').mean()
aggregate function (e.g., mean,
sum) on the groups.

Merges two DataFrames on a key


Merge pd.merge(df1, df2, on='key_column')
column, similar to SQL joins.

Concatenates two DataFrames


Concat pd.concat([df1, df2], axis=0) along a particular axis (rows or
columns).

Creates a pivot table, summarizing


df.pivot_table(values, index, columns, data based on specified index and
Pivot Table
aggfunc) columns with an aggregation
function (e.g., sum, mean).

Apply Applies a function to each element


df['column_name'].apply(function)
Function in a column.

Returns a DataFrame of the same


Isnull df.isnull() shape indicating whether each
element is NaN or not.

Removes rows or columns with


Dropna df.dropna()
NaN values.

Replaces NaN values with a


Fillna df.fillna(value)
specified value.

Value Returns the count of unique values


df['column_name'].value_counts()
Counts in a column.
Command
Syntax Definition/Operation
Name

Returns an array of unique values


Unique df['column_name'].unique()
in a column.

Plots data from a DataFrame


Plot df['column_name'].plot()
column using Matplotlib.

Resamples time-series data (e.g.,


Resample df.resample('frequency').mean() converting daily data to monthly)
and applies an aggregate function.

Calculates a rolling statistic (e.g.,


Rolling df['column_name'].rolling(window=n).mean() rolling mean) for a specified
window size.

You might also like