Popular Pandas snippets used in data analysis.
Pandas is very popular Python library for data analysis, manipulation, and visualization, I would like to share my personal view on the list of most often used functions/snippets for data analysis.
1.Import Pandas to Python
import pandas as pd
2. Import data from CSV/Excel file
df=pd.read_csv('C:/Folder/mlhype.csv') #imports whole csv to pd dataframe df = pd.read_csv('C:/Folder/mlhype.csv', usecols=['abv', 'ibu']) #imports selected columns df = pd.read_excel('C:/Folder/mlhype.xlsx') #imports excel file
3. Save data to CSV/Excel
df.to_csv('C:/Folder/mlhype.csv') #saves data frame to csv df.to_excel('C:/Folder/mlhype.xlsx') #saves data frame to excel
4. Exploring data
df.head(5) #returns top 5 rows of data df.tail(5) #returns bottom 5 rows of data df.sample(5) #returns random 5 rows of data df.shape #returns number of rows and columns df.info() #returns index,data types, memory information df.describe() #returns basic statistical summary of columns
5. Basic statistical functions
df.mean() #returns mean of columns df.corr() #returns correlation table df.count() #returns count of non-null's in column df.max() #returns max value in each column df.min() #returns min value in each column df.median() #returns median of each colun df.std() #returns standard deviation of each column
6. Selecting subsets
df['ColumnName'] #returns column 'ColumnName' df[['ColumnName1','ColumnName2']] #returns multiple columns from the list df.iloc[2,:] #selection by position - whole second row df.iloc[:,2] #selection by position - whole second column df.loc[:10,'ColumnName'] #returns first 11 rows of column df.ix[2,'ColumnName'] #returns second element of column
7. Data cleansing
df.columns = ['a','b','c','d','e','f','g','h'] #rename column names df.dropna() #drops all rows that contain missing values df.fillna(0) #replaces missing values with 0 (or any other passed value) df.fillna(df.mean()) #replaces missing values with mean(or any other passed function)
df[df['ColumnName'] > 0.08] #returns rows with meeting criterion df[(df['ColumnName1']>2004) & (df['ColumnName2']==9)] #returns rows meeting multiple criteria df.sort_values('ColumnName') #sorts by column in ascending order df.sort_values('ColumnName',ascending=False) #sort by column in descending order
9. Data frames concatenation
pd.concat([DateFrame1, DataFrame2],axis=0) #concatenate rows vertically pd.concat([DateFrame1, DataFrame2],axis=1) #concatenate rows horizontally
10.Adding new columns
df['NewColumn'] = 50 #creates new column with value 50 in each row df['NewColumn3'] = df['NewColumn1']+df['NewColumn2'] #new column with value equal to sum of other columns del df['NewColumn'] #deletes column
Was the above useful? Please share with others on social media.
Recommended reading list:
|Data Science from Scratch: First Principles with Python
Data science libraries, frameworks, modules, and toolkits are great for doing data science, but they’re also a good way to dive into the discipline without actually understanding data science. In this book, you’ll learn how many of the most fundamental data science tools and algorithms work by implementing them from scratch.
If you have an aptitude for mathematics and some programming skills, author Joel Grus will help you get comfortable with the math and statistics at the core of data science, and with hacking skills you need to get started as a data scientist. Today’s messy glut of data holds answers to questions no one’s even thought to ask. This book provides you with the know-how to dig those answers out.
Get a crash course in Python
Learn the basics of linear algebra, statistics, and probability—and understand how and when they're used in data science
Collect, explore, clean, munge, and manipulate data
Dive into the fundamentals of machine learning
Implement models such as k-nearest Neighbors, Naive Bayes, linear and logistic regression, decision trees, neural networks, and clustering
Explore recommender systems, natural language processing, network analysis, MapReduce, and databases
|Practical Statistics for Data Scientists: 50 Essential Concepts
Statistical methods are a key part of of data science, yet very few data scientists have any formal statistics training. Courses and books on basic statistics rarely cover the topic from a data science perspective. This practical guide explains how to apply various statistical methods to data science, tells you how to avoid their misuse, and gives you advice on what's important and what's not.
Many data science resources incorporate statistical methods but lack a deeper statistical perspective. If you’re familiar with the R programming language, and have some exposure to statistics, this quick reference bridges the gap in an accessible, readable format.
With this book, you’ll learn:
Why exploratory data analysis is a key preliminary step in data science
How random sampling can reduce bias and yield a higher quality dataset, even with big data
How the principles of experimental design yield definitive answers to questions
How to use regression to estimate outcomes and detect anomalies
Key classification techniques for predicting which categories a record belongs to
Statistical machine learning methods that “learn” from data
Unsupervised learning methods for extracting meaning from unlabeled data
|Doing Data Science: Straight Talk from the Frontline
Now that people are aware that data can make the difference in an election or a business model, data science as an occupation is gaining ground. But how can you get started working in a wide-ranging, interdisciplinary field that’s so clouded in hype? This insightful book, based on Columbia University’s Introduction to Data Science class, tells you what you need to know.
In many of these chapter-long lectures, data scientists from companies such as Google, Microsoft, and eBay share new algorithms, methods, and models by presenting case studies and the code they use. If you’re familiar with linear algebra, probability, and statistics, and have programming experience, this book is an ideal introduction to data science.
Statistical inference, exploratory data analysis, and the data science process
Spam filters, Naive Bayes, and data wrangling
Recommendation engines and causality
Social networks and data journalism
Data engineering, MapReduce, Pregel, and Hadoop
|The Data Science Handbook: Advice and Insights from 25 Amazing Data Scientists
The Data Science Handbook contains interviews with 25 of the world s best data scientists. We sat down with them, had in-depth conversations about their careers, personal stories, perspectives on data science and life advice. In The Data Science Handbook, you will find war stories from DJ Patil, US Chief Data Officer and one of the founders of the field. You ll learn industry veterans such as Kevin Novak and Riley Newman, who head the data science teams at Uber and Airbnb respectively. You ll also read about rising data scientists such as Clare Corthell, who crafted her own open source data science masters program. This book is perfect for aspiring or current data scientists to learn from the best. It s a reference book packed full of strategies, suggestions and recipes to launch and grow your own data science career.
|Introduction to Machine Learning with Python: A Guide for Data Scientists
Machine learning has become an integral part of many commercial applications and research projects, but this field is not exclusive to large companies with extensive research teams. If you use Python, even as a beginner, this book will teach you practical ways to build your own machine learning solutions. With all the data available today, machine learning applications are limited only by your imagination.
You’ll learn the steps necessary to create a successful machine-learning application with Python and the scikit-learn library. Authors Andreas Müller and Sarah Guido focus on the practical aspects of using machine learning algorithms, rather than the math behind them. Familiarity with the NumPy and matplotlib libraries will help you get even more from this book.
With this book, you’ll learn:
Fundamental concepts and applications of machine learning
Advantages and shortcomings of widely used machine learning algorithms
How to represent data processed by machine learning, including which data aspects to focus on
Advanced methods for model evaluation and parameter tuning
The concept of pipelines for chaining models and encapsulating your workflow
Methods for working with text data, including text-specific processing techniques
Suggestions for improving your machine learning and data science skills