\documentclass[10pt,a4paper]{article} % Packages \usepackage{fancyhdr} % For header and footer \usepackage{multicol} % Allows multicols in tables \usepackage{tabularx} % Intelligent column widths \usepackage{tabulary} % Used in header and footer \usepackage{hhline} % Border under tables \usepackage{graphicx} % For images \usepackage{xcolor} % For hex colours %\usepackage[utf8x]{inputenc} % For unicode character support \usepackage[T1]{fontenc} % Without this we get weird character replacements \usepackage{colortbl} % For coloured tables \usepackage{setspace} % For line height \usepackage{lastpage} % Needed for total page number \usepackage{seqsplit} % Splits long words. %\usepackage{opensans} % Can't make this work so far. Shame. Would be lovely. \usepackage[normalem]{ulem} % For underlining links % Most of the following are not required for the majority % of cheat sheets but are needed for some symbol support. \usepackage{amsmath} % Symbols \usepackage{MnSymbol} % Symbols \usepackage{wasysym} % Symbols %\usepackage[english,german,french,spanish,italian]{babel} % Languages % Document Info \author{datamansam} \pdfinfo{ /Title (data-flow-with-python.pdf) /Creator (Cheatography) /Author (datamansam) /Subject (Data Flow with Python Cheat Sheet) } % Lengths and widths \addtolength{\textwidth}{6cm} \addtolength{\textheight}{-1cm} \addtolength{\hoffset}{-3cm} \addtolength{\voffset}{-2cm} \setlength{\tabcolsep}{0.2cm} % Space between columns \setlength{\headsep}{-12pt} % Reduce space between header and content \setlength{\headheight}{85pt} % If less, LaTeX automatically increases it \renewcommand{\footrulewidth}{0pt} % Remove footer line \renewcommand{\headrulewidth}{0pt} % Remove header line \renewcommand{\seqinsert}{\ifmmode\allowbreak\else\-\fi} % Hyphens in seqsplit % This two commands together give roughly % the right line height in the tables \renewcommand{\arraystretch}{1.3} \onehalfspacing % Commands \newcommand{\SetRowColor}[1]{\noalign{\gdef\RowColorName{#1}}\rowcolor{\RowColorName}} % Shortcut for row colour \newcommand{\mymulticolumn}[3]{\multicolumn{#1}{>{\columncolor{\RowColorName}}#2}{#3}} % For coloured multi-cols \newcolumntype{x}[1]{>{\raggedright}p{#1}} % New column types for ragged-right paragraph columns \newcommand{\tn}{\tabularnewline} % Required as custom column type in use % Font and Colours \definecolor{HeadBackground}{HTML}{333333} \definecolor{FootBackground}{HTML}{666666} \definecolor{TextColor}{HTML}{333333} \definecolor{DarkBackground}{HTML}{A3A3A3} \definecolor{LightBackground}{HTML}{F3F3F3} \renewcommand{\familydefault}{\sfdefault} \color{TextColor} % Header and Footer \pagestyle{fancy} \fancyhead{} % Set header to blank \fancyfoot{} % Set footer to blank \fancyhead[L]{ \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{C} \SetRowColor{DarkBackground} \vspace{-7pt} {\parbox{\dimexpr\textwidth-2\fboxsep\relax}{\noindent \hspace*{-6pt}\includegraphics[width=5.8cm]{/web/www.cheatography.com/public/images/cheatography_logo.pdf}} } \end{tabulary} \columnbreak \begin{tabulary}{11cm}{L} \vspace{-2pt}\large{\bf{\textcolor{DarkBackground}{\textrm{Data Flow with Python Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{datamansam} via \textcolor{DarkBackground}{\uline{cheatography.com/139410/cs/32160/}}} \end{tabulary} \end{multicols}} \fancyfoot[L]{ \footnotesize \noindent \begin{multicols}{3} \begin{tabulary}{5.8cm}{LL} \SetRowColor{FootBackground} \mymulticolumn{2}{p{5.377cm}}{\bf\textcolor{white}{Cheatographer}} \\ \vspace{-2pt}datamansam \\ \uline{cheatography.com/datamansam} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Published 3rd September, 2022.\\ Updated 3rd September, 2022.\\ Page {\thepage} of \pageref{LastPage}. \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Sponsor}} \\ \SetRowColor{white} \vspace{-5pt} %\includegraphics[width=48px,height=48px]{dave.jpeg} Measure your website readability!\\ www.readability-score.com \end{tabulary} \end{multicols}} \begin{document} \raggedright \raggedcolumns % Set font size to small. Switch to any value % from this page to resize cheat sheet text: % www.emerson.emory.edu/services/latex/latex_169.html \footnotesize % Small font. \begin{multicols*}{3} \begin{tabularx}{5.377cm}{x{1.19002 cm} x{2.05965 cm} x{1.32733 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{Comprehensions}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{3}{x{5.377cm}}{List:} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} name of new list = & {[}expression for item in iterable & if condition == True{]} \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} squares = & {[}number**2 for number in numbers & if x \textless{} 5{]} \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{3}{x{5.377cm}}{Generators:} \tn % Row Count 6 (+ 1) % Row 4 \SetRowColor{LightBackground} & use () & not {[}{]} \tn % Row Count 7 (+ 1) % Row 5 \SetRowColor{white} \seqsplit{print(next(result))} & \seqsplit{print(next(result))} & \tn % Row Count 9 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Dictionaries}} \tn \SetRowColor{white} \mymulticolumn{1}{x{5.377cm}}{for x, y in art\_galleries.items(): \newline % Row Count 1 (+ 1) print(x) \newline % Row Count 2 (+ 1) print(y) \newline % Row Count 3 (+ 1) \# x with return keys, \newline % Row Count 4 (+ 1) y values% Row Count 5 (+ 1) } \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{2.4885 cm} x{2.4885 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Set Functions to process Iterable Objects}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Create sets from a list:} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{cookies \_ eaten \_ today = {[}'chocolate chip' , 'peanut butter' , ...: 'chocolate chip' , 'oatmeal cream' , 'chocolate chip'{]}} \tn % Row Count 4 (+ 3) % Row 2 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{types \_ of \_ cookies \_ eaten = set(cookies \_ eaten \_ today)} \tn % Row Count 6 (+ 2) % Row 3 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{Adding elements to a set:} \tn % Row Count 7 (+ 1) % Row 4 \SetRowColor{LightBackground} .add() adds single elements & types \_ of \_ cookies \_ \seqsplit{eaten.add('biscotti')} \tn % Row Count 10 (+ 3) % Row 5 \SetRowColor{white} .update() merges in another set or list & types \_ of \_ cookies \_ \seqsplit{eaten.update(cookies} \_ we\_will\_ eeat) \tn % Row Count 13 (+ 3) % Row 6 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Removing:} \tn % Row Count 14 (+ 1) % Row 7 \SetRowColor{white} .discard() safely removes an element from the set by value & types \_ of \_ cookies \_ \seqsplit{eaten.discard('biscotti')} \tn % Row Count 17 (+ 3) % Row 8 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Combining Sets:} \tn % Row Count 18 (+ 1) % Row 9 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{.union() returns a set of all the unique values} \tn % Row Count 19 (+ 1) % Row 10 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{cookies \_jason \_ ate.union(cookies \_ hugo \_ ate)} \tn % Row Count 20 (+ 1) % Row 11 \SetRowColor{white} \mymulticolumn{2}{x{5.377cm}}{.intersection() method identies overlapping data} \tn % Row Count 21 (+ 1) % Row 12 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{cookies \_jason \_ ate.intersection(cookies \_ hugo \_ ate)} \tn % Row Count 23 (+ 2) % Row 13 \SetRowColor{white} .difference() method identies data present in the set on which the method was used that is not in the arguments ( - ) & cookies \_jason \_ \seqsplit{ate.difference(cookies} \_ hugo \_ ate) \tn % Row Count 29 (+ 6) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.64241 cm} x{3.33459 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{5.377cm}}{\bf\textcolor{white}{Lambda Functions}} \tn % Row 0 \SetRowColor{LightBackground} \mymulticolumn{2}{x{5.377cm}}{Syntax:} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \seqsplit{LambdaFunctionName} = & arguments : expression \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{DefineFunction} = & lambda (param1, paramn: param1 ** paramn) \tn % Row Count 5 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Using a Lamda Function inside another Function}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\# a function that always doubles the number you send in \newline def myfunc(n): \newline return lambda a : a * n \newline \newline mydoubler = myfunc(2) \newline \newline print(mydoubler(11))} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Lambda with Map}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\# Create a list of strings: spells \newline spells = {[}"protego", "accio", "expecto patronum", "legilimens"{]} \newline \newline \# Use map() to apply a lambda function over spells: shout\_spells \newline shout\_spells = map(lambda item: item + '!!!' , spells) \newline \newline \# Convert shout\_spells to a list: shout\_spells\_list \newline shout\_spells\_list = list(shout\_spells) \newline \newline \# Print the result \newline print(shout\_spells\_list)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Reduce}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\# Import reduce from functools \newline from functools import reduce \newline \newline \# Create a list of strings: stark \newline stark = {[}'robb', 'sansa', 'arya', 'brandon', 'rickon'{]} \newline \newline \# Use reduce() to apply a lambda function over stark: result \newline result = reduce(lambda item1, item2: item1 + item2, stark) \newline \newline \# Print the result \newline print(result)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Filter}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{nums = {[}1, 2, 3, 4, 5, 6, 7, 8, 9, 10{]} \newline print("Original list of integers:") \newline print(nums) \newline print("\textbackslash{}Resuls less than 3 when divided by 2 from the said list:") \newline LessThan3 = list(filter(lambda x: x//2 \textless{} 3, nums)) \newline print(LessThan3)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Iterating through DataFrame Columns}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\# Extract column from DataFrame: col \newline col = df{[}col\_name{]} \newline \newline \# Iterate over each column in DataFrame \newline for entry in col: \newline action} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Iterating through DataFrames}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{\# Define count\_entries() \newline def count\_entries(df, col\_name='lang'): \newline """Return a dictionary with counts of \newline occurrences as value for each key.""" \newline \newline \# Initialize an empty dictionary: cols\_count \newline cols\_count = \{\} \newline \newline \# Add try block \newline try : \newline \# Extract column from DataFrame: col \newline col = df{[}col\_name{]} \newline \newline \# Iterate over each column in DataFrame \newline for entry in col: \newline \newline \# If entry is in cols\_count, add 1 \newline if entry in cols\_count.keys(): \newline cols\_count{[}entry{]} += 1 \newline \# Else add the entry to cols\_count, set the value to 1 \newline else: \newline cols\_count{[}entry{]} = 1 \newline \newline \# Return the cols\_count dictionary \newline return cols\_count \newline \newline \# Add except block \newline except: \newline pass \newline \newline \# Call count\_entries(): result1 \newline result1 = \seqsplit{count\_entries(tweets\_df}, 'lang') \newline \newline \# Print result1 \newline print(result1)} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{x{1.55618 cm} x{1.51041 cm} x{1.51041 cm} } \SetRowColor{DarkBackground} \mymulticolumn{3}{x{5.377cm}}{\bf\textcolor{white}{apply, applymap and map}} \tn % Row 0 \SetRowColor{LightBackground} Apply: & Applymap: & Map: \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} to apply a function along the axis of a dataframe, & element wise operation across one or more rows and columns of a dataframe. & Substitutes the series value from the lookup dictionary, Series or a function \tn % Row Count 7 (+ 6) % Row 2 \SetRowColor{LightBackground} DFs and Series & Only Dataframes & Used only for a Series object \tn % Row Count 10 (+ 3) % Row 3 \SetRowColor{white} Applied to both series and elements & Applied to elements individually & Applied to series \tn % Row Count 13 (+ 3) \hhline{>{\arrayrulecolor{DarkBackground}}---} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{5.377cm}{X} \SetRowColor{DarkBackground} \mymulticolumn{1}{x{5.377cm}}{\bf\textcolor{white}{Code Eamples of apply, applymap and map}} \tn \SetRowColor{LightBackground} \mymulticolumn{1}{x{5.377cm}}{df.apply(np.sum, axis=0) \newline -\textgreater{} col sums \newline \newline df.apply(np.sum, axis=1) \newline -\textgreater{} row sums \newline \newline \newline df.applymap(lambda x: x**2) \newline -\textgreater{} Every df element squared \newline \newline \newline s = pd.Series({[}'cat', 'dog', np.nan, 'rabbit'{]}) \newline s.map(\{'cat': 'kitten', 'dog': 'puppy'\})} \tn \hhline{>{\arrayrulecolor{DarkBackground}}-} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}