15 Essential Python Pandas Code Snippets for Data Scientists

<p>Python&rsquo;s Pandas library is a fundamental tool for data scientists, offering powerful data manipulation and analysis capabilities. In this article, we&rsquo;ll explore 15 advanced Pandas code snippets that every data scientist should have in their toolkit. These snippets will help you streamline your data analysis tasks and extract valuable insights from your datasets.</p> <p>&nbsp;</p> <h1>1. Filtering Data</h1> <pre> import pandas as pd # Create a DataFrame data = {&#39;Name&#39;: [&#39;Alice&#39;, &#39;Bob&#39;, &#39;Charlie&#39;, &#39;David&#39;], &#39;Age&#39;: [25, 30, 35, 40]} df = pd.DataFrame(data) # Filter rows where Age is greater than 30 filtered_df = df[df[&#39;Age&#39;] &gt; 30] print(filtered_df)</pre> <h1>2. Grouping and Aggregating Data</h1> <pre> # Grouping by a column and calculating the mean grouped = df.groupby(&#39;Age&#39;).mean() print(grouped)</pre> <h1>3. Handling Missing Data</h1> <pre> # Check for missing values missing_values = df.isnull().sum() # Fill missing values with a specific value df[&#39;Age&#39;].fillna(0, inplace=True)</pre> <h1>4. Applying Functions to Columns</h1> <pre> # Applying a custom function to a column df[&#39;Age&#39;] = df[&#39;Age&#39;].apply(lambda x: x * 2)</pre> <h1>5. Concatenating DataFrames</h1> <pre> # Concatenate two DataFrames df1 = pd.DataFrame({&#39;A&#39;: [&#39;A0&#39;, &#39;A1&#39;], &#39;B&#39;: [&#39;B0&#39;, &#39;B1&#39;]}) df2 = pd.DataFrame({&#39;A&#39;: [&#39;A2&#39;, &#39;A3&#39;], &#39;B&#39;: [&#39;B2&#39;, &#39;B3&#39;]}) result = pd.concat([df1, df2], ignore_index=True) print(result)</pre> <h1>6. Merging DataFrames</h1> <pre> # Merge two DataFrames left = pd.DataFrame({&#39;key&#39;: [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;], &#39;value&#39;: [1, 2, 3]}) right = pd.DataFrame({&#39;key&#39;: [&#39;B&#39;, &#39;C&#39;, &#39;D&#39;], &#39;value&#39;: [4, 5, 6]}) merged = pd.merge(left, right, on=&#39;key&#39;, how=&#39;inner&#39;) print(merged)</pre> <h1>7. Pivot Tables</h1> <pre> # Creating a pivot table pivot_table = df.pivot_table(index=&#39;Name&#39;, columns=&#39;Age&#39;, values=&#39;Value&#39;) print(pivot_table)</pre> <h1>8. Handling DateTime Data</h1> <pre> # Converting a column to DateTime df[&#39;Date&#39;] = pd.to_datetime(df[&#39;Date&#39;])</pre> <h1>9. Reshaping Data</h1> <pre> # Melting a DataFrame melted_df = pd.melt(df, id_vars=[&#39;Name&#39;], value_vars=[&#39;A&#39;, &#39;B&#39;]) print(melted_df)</pre> <h1>10. Working with Categorical Data</h1> <pre> # Encoding categorical variables df[&#39;Category&#39;] = df[&#39;Category&#39;].astype(&#39;category&#39;) df[&#39;Category&#39;] = df[&#39;Category&#39;].cat.codes</pre> <p><a href="https://medium.com/@pythonfundamentals/15-essential-python-pandas-code-snippets-for-data-scientists-87bd499043a4">Visit Now</a></p>