pandas and openpyxl Cheat Sheet

A Programming › Python cheat sheet in English by Reszi

Python's pandas and openpyxl cheat sheet

10,337 views 1,674 downloads 28 Jan 2024 History

Read/Write and Inspection

Read/Write
{{lang-python}}df = pd.rea­d_e­xce­l('f­ile.xl­sx')
Read file (CSV, Excel, JSON, HTML, SQL)
{{lang-python}}df.to_csv('file.csv')
Write file
Inspection
{{lang-python}}df.head()/.tail()
View first/last rows
{{lang-python}}df.shape
Gives dimensions
{{lang-python}}df.dtypes
Shows types in each column (int, str etc)
{{lang-python}}df.info
Lists: (range of index, list of all columns, no. non null, data types, memory usage)
{{lang-python}}df.describe
Lists: (count, mean, std deviation, min, 25%, 50%, 75%, max)

Filter

Functi­onality
{{lang-python}}df[df['column] vs {{lang-python}}df['column']
1st filters dataframe, 2nd creates list of booleans
{{lang-python}}df[df[x] > y & df[df[a] > v
& combines filters
{{lang-python}}df[df.apply(lamba row: row['co­l1'] * 2 > row['co­l2'], axis=0)
Filter by function. Axis=0 for columns, 1 for rows.
{{lang-python}}df.reset_index(drop=True)
Reset indexs for filter
Rows and Columns
{{lang-python}}df[['column1', '­col­umn­2']]
Filter by columns
{{lang-python}}df.iloc[1:5]
Filter by row (2nd - 6th)
{{lang-python}}df[df['column'] > value
Filters rows based on boolean
{{lang-python}}df[df['column'].isin([value1, value2])
Filter rows based on list of values
{{lang-python}}df.query('age > @min_a­ge')
Filter rows based on query string, @ points to variable '­and­' to combine
{{lang-python}}df.loc[df['column'] > value, '­col­umn­_na­me']
Filters rows and columns
Dropping and replacing
{{lang-python}}df.drop(columns=['column1', '­col­um­­n2']­)' or
'{{lang-python}}df.drop(['unnecessary_column'], axis=1, inplac­e=True)
Drop columns
{{lang-python}}df.drop_duplicates(subset=['column'])
Drop duplicate rows from specific columns
{{lang-python}}df.dropna() vs {{lang-python}}.notna()
Removes rows with missing values­/no­n-m­issing values
{{lang-python}}df.mask/.where(df['column'] > value)
Replaces rows not meetin­g/m­eeting condition with NaN
String
{{lang-python}}df[df['column'].str.contains('substring')
Fitler where string column contains substring
{{lang-python}}df[df['column'].str.match(r'abc$')]
{{lang-python}}^abc: Start with '­abc­'; {{lang-python}}abc$: End with '­abc­'; {{lang-python}}a|b: '­a' or '­b'; {{lang-python}}abc+: '­abc­' followed by 1+ '­c's; {{lang-python}}abc*: '­ab' followed by 0+ '­c's; {{lang-python}}abc?: '­ab' followed by 0 or 1 '­c'; {{lang-python}}[abc]: Any one of '­a', '­b', or '­c'

Data Manipu­lation

Editing data
{{lang-python}}df['new_column'] = new_values
Assign­/create new values for column
{{lang-python}}df['column'] *= value
Multiply (/=, -= , +=) each entry in a column by a value.
{{lang-python}}df.fillna(value or method)
Fill Nan values
{{lang-python}}df['column'].replace(to_replace, value)
Replace values
{{lang-python}}df['column'].rolling(window=7).mean()
Rolling aggregate
{{lang-python}}df.update(other_df)
Updates values from other df
{{lang-python}}df['column'].astype(dtype)
Converts data type
{{lang-python}}np.where(df['column']> value, '­Val­ue=­Tru­e', '­Val­ue=­Fal­se')
Create array based on new conditions
{{lang-python}}df['column'].apply(lambda/function name))
Apply functions to selection
{{lang-python}}df.rename(columns={'old_name': '­new­_na­me'})
Rename columns
Combining data
{{lang-python}}pd.merge(df1,df2, on='­common column­', how='in­ner­')or
{{lang-python}}pd.merge(df1, df2, left_i­nde­x=True, right_­ind­ex=­True, how='ou­ter­')
Merges two dfs based on a common column. '­inn­er' requires both df to have all columns filled vs '­outer, '­lef­t' vs '­rig­ht' to filter for columns of either df
{{lang-python}}pd.concat([df1, df2])
Concat­enate (combines all values)
{{lang-python}}df['column'].map(mapping_dict)
Create a dictionary from a list to map keys and values to each other

Group by

Group by
{{lang-python}}grouped = df.gro­upb­y([­'­Sto­re', '­Pro­duc­t']).ag­g(T­ota­l_S­ale­s=(­'­Sal­es',­'sum) Averag­e_C­ost­=('C­ost­', '­mea­n'), Sales_­Cou­nt=­('Sa­les­', '­cou­nt'))
{{lang-python}}filtered_grouped = groupe­d[g­rou­ped­['To­tal­_Sa­les­'] > 500]
Aggreg­ations: {{lang-python}}sum; mean; median; min; max; count; size; std (standard deviation); var (variance); first; last; prod or product; nunique(number of unique values)

Pivot

Pivot
{{lang-python}}pivoted_df = df.piv­ot(­ind­ex=­'­Dat­e', column­s='V­ari­abl­e', values­='Va­lue­')
{{lang-python}}pivot_table_df = df.piv­ot_­tab­le(­ind­ex=­'­Dat­e', column­s='V­ari­abl­e', values­='Va­lue­', aggfun­c='s­um')

values (optio­nal): Columns whose data will be aggreg­ated.
index: Columns used as index.
columns (optio­nal): Columns to pivot into new DataFr­ame­'s columns.
aggfunc: Aggreg­ation function for values.
pivot_­table: aggregates duplicates

Melt

Melt
{{lang-python}} melted_df = pd.mel­t(df, id_var­s=[­'­id_­col­umn­'], var_na­me=­'­var­iab­le_­nam­e', value_­nam­e='v­alu­e_n­ame­')
id_vars (optio­nal): Columns to keep unchanged. Otherwise default melted
value_vars (optio­nal): Columns to melt.
var_name (optio­nal): Melted column name. Default is '­var­iab­le'.
value_name (optio­nal): Melted values column name. Default is '­val­ue'.
col_level (optio­nal): Multi-­index level

Stack/­unstack

Stack/unstack
stacked_df = df.sta­ck(­lev­el=-1, dropna­=True)
Level: The level(s) of the column labels you want to stack. The default is the last level.
Dropna: Whether to drop rows in the resulting DataFrame with missing values. Default is True.

Time Operations

{{lang-python}}pd.to_datetime(df['column'])
Converts a column to datetime format
{{lang-python}}pd.Timestamp.now()
Returns the current date and time
{{lang-python}}df['datetime_column'].dt.date/.time
Extracts the date/time from a datetime column
{{lang-python}}datetime.datetime.strptime(date_string, format)
Useful for strings with words and dates, or including hours/­min­utes, or multiple dates types in one column (requires try except function)

Open pyxl

{{lang-python}}openpyxl.load_workbook(filename)
workbo­ok.s­av­e(f­ile­name)
Read/Write
{{lang-python}}workbook[sheetname] or workbo­ok.a­ctive
Sheet selection
Cell Formats
{{lang-python}}cell.font = Font(s­ize=12)
Font
{{lang-python}}cell.number_format = '­0.0­0%'
Cell formats
{{lang-python}}Alignment(horizontal="center");
Border­(le­ft=­Sid­e(b­ord­er_­sty­le=­"­thi­n", color=­"­000­000­");
Patter­nFi­ll(­"­sol­id", fgColo­r="D­DDD­DD")
More cell options
{{lang-python}}Comment('Text', '­Aut­hor­')
Cell Comments, can change commen­t.w­idt­h/h­eight too.
{{lang-python}}sheet.unmerge/merge_cells('A1:D1')
Merge/­Unmerge
{{lang-python}}cell.hyperlink = '­htt­p:/­/ww­w.e­xam­ple.co­m'
Hyperlinks
{{lang-python}}ColorScaleRule(start_type="min", start_­col­or=­"­FFF­FFF­", end_ty­pe=­"­max­", end_co­lor­="FF­000­0")
ws.con­dit­ion­al_­for­mat­tin­g.a­dd(­"­A1:­A9", rule)
Condit­ional Formatting
{{lang-python}}DataValidation(type="list", formul­a1=­'­"­Ite­m1,­Ite­m2,­Ite­m3"', showDr­opD­own­=True)
ws.add­_da­ta_­val­ida­tio­n(dv)
Data validation
Charts
{{lang-python}}chart = BarCha­rt(),
chart.s­tyle = 13,
sheet.a­dd­_ch­art­(chart)
Create, style, then add chart to sheet
{{lang-python}}Image('path/to/image'), sheet.a­dd­_im­age­(img, '­A1')
Add images, better for mathplot or other libraries
{{lang-python}}cell.value = '­=SU­M(A­1:A­10)­'
Write formulas

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.