\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{AdrianPerogil} \pdfinfo{ /Title (pandas-chopito.pdf) /Creator (Cheatography) /Author (AdrianPerogil) /Subject (Pandas - Chopito 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{Pandas - Chopito Cheat Sheet}}}} \\ \normalsize{by \textcolor{DarkBackground}{AdrianPerogil} via \textcolor{DarkBackground}{\uline{cheatography.com/195296/cs/44826/}}} \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}AdrianPerogil \\ \uline{cheatography.com/adrianperogil} \\ \end{tabulary} \vfill \columnbreak \begin{tabulary}{5.8cm}{L} \SetRowColor{FootBackground} \mymulticolumn{1}{p{5.377cm}}{\bf\textcolor{white}{Cheat Sheet}} \\ \vspace{-2pt}Not Yet Published.\\ Updated 28th October, 2024.\\ 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*}{2} \begin{tabularx}{8.4cm}{x{2.72 cm} x{5.28 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Init}} \tn % Row 0 \SetRowColor{LightBackground} {\bf{import}} & import pandas as pd \tn % Row Count 1 (+ 1) \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{1.6 cm} x{6.4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Creating Reading Writing}} \tn % Row 0 \SetRowColor{LightBackground} \seqsplit{read\_csv()} & \seqsplit{pd.read\_csv('example.csv'}, index\_col=0, usecols={[}'title'{]}, sep=';') \tn % Row Count 3 (+ 3) % Row 1 \SetRowColor{white} \seqsplit{to\_csv()} & df.to\_csv('example.csv', index=False, sep=';', header=False) \tn % Row Count 5 (+ 2) % Row 2 \SetRowColor{LightBackground} head() & df.head(5) \tn % Row Count 6 (+ 1) % Row 3 \SetRowColor{white} copy() & df\_copy = df{[}{[}'title', 'year'{]}{]}.copy() \tn % Row Count 8 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{index\_col=0}}: La primera columna del df, será el índice. \newline {\bf{ usecols={[}'title'{]}}}: Solo carga del df, la columna title. \newline {\bf{sep=';'}}:Tipo de separador que contiene el CSV. \newline {\bf{header=False}}: No contiene una fila con nombres de la columna, se sustituyen por números. \newline {\bf{index=False}}: Solo se guardan las columnas. \newline {\bf{copy()}}: Cambiar en df\_copy, no afecta a df. Sin copy, crea una referencia de df, cambios en df\_copia puede afectar a df.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.32 cm} x{5.68 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Indexing Selecting Assigning}} \tn % Row 0 \SetRowColor{LightBackground} loc() & df.loc{[}df{[}'year'{]} \textgreater{}= 2018{]} \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} loc() with == & df.loc{[}df{[}'title'{]} == 'Black Panther', 'people\_score'{]} = 100 \tn % Row Count 4 (+ 3) % Row 2 \SetRowColor{LightBackground} loc() with \& & df.loc{[}(df{[}'critic\_score'{]} \textgreater{} 90) \& (df{[}'people\_score'{]} \textgreater{} 80){]} \tn % Row Count 7 (+ 3) % Row 3 \SetRowColor{white} \seqsplit{str.startswith()} & df.loc{[}df{[}'title'{]}.str.startswith('S'){]} \tn % Row Count 9 (+ 2) % Row 4 \SetRowColor{LightBackground} \seqsplit{str.contain()} & df.loc{[}df{[}'title'{]}.str.contains('Spider'), 'critic\_score'{]} = 95 \tn % Row Count 12 (+ 3) % Row 5 \SetRowColor{white} iloc() & df.iloc{[}5:11, {[}0, 1, 3{]}{]} \tn % Row Count 13 (+ 1) % Row 6 \SetRowColor{LightBackground} subtract & df{[}'critic\_score'{]} - df{[}'people\_score'{]} \tn % Row Count 15 (+ 2) % Row 7 \SetRowColor{white} median() & df.loc{[}df{[}'critic\_score'{]} \textgreater{} df{[}'critic\_score'{]}.median(){]} \tn % Row Count 17 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{loc()}}: Selecciona filas y columnas basado en una etiqueta, en este caso los que cumplan x condición. \newline {\bf{iloc()}}: Selecciona filas y columnas basado en su índice, en este caso las filas del 5 al 10 y las columnas 0, 1, 3. \newline {\bf{str.startswith()}}: En este caso, selecicona las películas cuyo título comience por S. \newline {\bf{str.contains()}}: En este caso, selecicona las películas cuyo título contengan 'Spider'. \newline {\bf{median()}}: Hace la mediana de la columna 'critic\_score'} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.08 cm} x{5.92 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Summary Functions Maps}} \tn % Row 0 \SetRowColor{LightBackground} mean() & df{[}'critic\_score'{]}.mean() \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} \seqsplit{describe()} & df.describe() \tn % Row Count 2 (+ 1) % Row 2 \SetRowColor{LightBackground} \seqsplit{value\_counts()} & df{[}'type'{]}.value\_counts() \tn % Row Count 4 (+ 2) % Row 3 \SetRowColor{white} min() & df{[}'people\_score'{]}.min() \tn % Row Count 5 (+ 1) % Row 4 \SetRowColor{LightBackground} max() & df{[}'people\_score'{]}.max() \tn % Row Count 6 (+ 1) % Row 5 \SetRowColor{white} def & def score\_ratio(row): \tn % Row Count 7 (+ 1) % Row 6 \SetRowColor{LightBackground} & newcolumn = row{[}'critic\_score'{]} / row{[}'people\_score'{]} \tn % Row Count 9 (+ 2) % Row 7 \SetRowColor{white} & return newcolumn \tn % Row Count 10 (+ 1) % Row 8 \SetRowColor{LightBackground} apply() & df{[}'score\_ratio'{]} = df.apply(score\_ratio, axis=1) \tn % Row Count 12 (+ 2) % Row 9 \SetRowColor{white} map() & df{[}'type'{]} = df{[}'type'{]}.map(lambda x: x.lower()) \tn % Row Count 14 (+ 2) % Row 10 \SetRowColor{LightBackground} std() & df{[}'people\_score'{]}.std() \tn % Row Count 15 (+ 1) % Row 11 \SetRowColor{white} agg() & critic\_score\_agg = df{[}'critic\_score'{]}.agg({[}'mean', 'std'{]}) \tn % Row Count 17 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{mean()}}: Calcula la media. \newline {\bf{describe()}}: Resumen estadístico del df. \newline {\bf{value\_counts()}}: Cuenta cuantas películas hay de cada tipo. \newline {\bf{apply()}}: En la columna nueva (score\_ratio) los valores se obtendrán por la función 'score\_ratio'. \newline {\bf{map()}}: Cambia todos los valores a minúscula con {\bf{lower()}}. \newline {\bf{std()}}: Mide la dispersión de los datos respecto a la media. \newline {\bf{agg()}}: Calcula múltiples estadísticas a la vez (mean y std).} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{4 cm} x{4 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Grouping Sorting}} \tn % Row 0 \SetRowColor{LightBackground} sort\_values() with loc() & \seqsplit{df.sort\_values('year')}.loc{[}:, {[}'title', 'year', 'critic\_score'{]}{]} \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} sort\_values() with agg() & df.groupby('type').agg(\{'critic\_score': {[}'mean', 'std'{]}\}) \tn % Row Count 7 (+ 3) % Row 2 \SetRowColor{LightBackground} groupby() with sum() & df.groupby('production\_co'){[}'people\_score'{]}.sum() \tn % Row Count 10 (+ 3) % Row 3 \SetRowColor{white} groupby() with size() & \seqsplit{df.groupby('year').size()} \tn % Row Count 12 (+ 2) % Row 4 \SetRowColor{LightBackground} groupby() with mean() and sort\_values() and sort\_values() & \seqsplit{df.groupby('production\_co').mean(numeric\_only=True).sort\_values('critic\_score'}, ascending=False) \tn % Row Count 17 (+ 5) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{df.groupby('production\_co').mean(numeric\_only=True).sort\_values('critic\_score', ascending=False)}}: Agrupa por columna, calcula la media de columnas numéricas y ordena por la columna 'critic\_score' de mayor a menos.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.56 cm} x{5.44 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Data\_type Missing\_values}} \tn % Row 0 \SetRowColor{LightBackground} astype() & df{[}'year'{]}.astype(str) \tn % Row Count 1 (+ 1) % Row 1 \SetRowColor{white} & df{[}'critic\_score'{]}.astype(float) \tn % Row Count 3 (+ 2) % Row 2 \SetRowColor{LightBackground} isnull() with sum() & df.isnull().sum() \tn % Row Count 5 (+ 2) % Row 3 \SetRowColor{white} fillna() & df{[}'people\_score'{]}.fillna(df{[}'people\_score'{]}.median()) \tn % Row Count 7 (+ 2) % Row 4 \SetRowColor{LightBackground} & df{[}'people\_score'{]}.fillna(0) \tn % Row Count 9 (+ 2) % Row 5 \SetRowColor{white} dropna() & df.dropna(subset={[}'critic\_score'{]}) \tn % Row Count 11 (+ 2) % Row 6 \SetRowColor{LightBackground} \seqsplit{str.replace()} & df{[}'release\_date\_(theaters)'{]}.str.replace('wide', \seqsplit{'').str.replace('limited'}, '') \tn % Row Count 14 (+ 3) % Row 7 \SetRowColor{white} \seqsplit{to\_datetime()} & pd.to\_datetime(df{[}'release\_date\_(theaters)'{]}) \tn % Row Count 16 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{astype()}}: convierte una columna a otro tipo de dato. \newline {\bf{isnull()}}: detecta valores nulos en el DataFrame. \newline {\bf{fillna()}}: reemplaza valores nulos con un valor especificado. \newline {\bf{dropna()}}: elimina filas o columnas con valores nulos. \newline {\bf{str.replace()}}: reemplaza patrones en texto dentro de una serie. \newline {\bf{to\_datetime()}}: convierte datos a formato de fecha y hora.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} \begin{tabularx}{8.4cm}{x{2.16 cm} x{5.84 cm} } \SetRowColor{DarkBackground} \mymulticolumn{2}{x{8.4cm}}{\bf\textcolor{white}{Renaming Combining}} \tn % Row 0 \SetRowColor{LightBackground} rename() & movies.rename(columns=\{'title': 'movie\_title', 'release\_year': 'release\_year'\}, inplace=True) \tn % Row Count 4 (+ 4) % Row 1 \SetRowColor{white} concat() & pd.concat({[}movies\_info, box\_office{]}, axis=1) \tn % Row Count 6 (+ 2) % Row 2 \SetRowColor{LightBackground} \seqsplit{set\_index()} & movies.set\_index('id') \tn % Row Count 8 (+ 2) % Row 3 \SetRowColor{white} join() & \seqsplit{movies.join(reviews.set\_index('id'))} \tn % Row Count 10 (+ 2) % Row 4 \SetRowColor{LightBackground} \seqsplit{df.index.name} & movies.index.name = 'movies\_index' \tn % Row Count 12 (+ 2) % Row 5 \SetRowColor{white} \seqsplit{df.columns.name} & movies.columns.name = 'movie\_attributes' \tn % Row Count 14 (+ 2) \hhline{>{\arrayrulecolor{DarkBackground}}--} \SetRowColor{LightBackground} \mymulticolumn{2}{x{8.4cm}}{{\bf{rename()}}: cambia nombres de columnas o índices en el DataFrame. \newline {\bf{concat()}}: une múltiples DataFrames a lo largo de un eje. \newline {\bf{set\_index()}}: establece una columna como índice del DataFrame. \newline {\bf{join()}}: combina DataFrames usando el índice. \newline {\bf{df.index.name}}: asigna o muestra el nombre del índice. \newline {\bf{df.columns.name}}: asigna o muestra el nombre de las columnas.} \tn \hhline{>{\arrayrulecolor{DarkBackground}}--} \end{tabularx} \par\addvspace{1.3em} % That's all folks \end{multicols*} \end{document}