Comparison with SAS¶
For potential users coming from SAS this page is meant to demonstrate how different SAS operations would be performed in pandas.
If you’re new to pandas, you might want to first read through 10 Minutes to pandas to familiarize yourself with the library.
As is customary, we import pandas and numpy as follows:
In [1]: import pandas as pd
In [2]: import numpy as np
Note
Throughout this tutorial, the pandas DataFrame
will be displayed by calling
df.head()
, which displays the first N (default 5) rows of the DataFrame
.
This is often used in interactive work (e.g. Jupyter notebook or terminal) - the equivalent in SAS would be:
proc print data=df(obs=5);
run;
Data Structures¶
General Terminology Translation¶
pandas | SAS |
---|---|
DataFrame |
data set |
column | variable |
row | observation |
groupby | BY-group |
NaN |
. |
DataFrame
/ Series
¶
A DataFrame
in pandas is analogous to a SAS data set - a two-dimensional
data source with labeled columns that can be of different types. As will be
shown in this document, almost any operation that can be applied to a data set
using SAS’s DATA
step, can also be accomplished in pandas.
A Series
is the data structure that represents one column of a
DataFrame
. SAS doesn’t have a separate data structure for a single column,
but in general, working with a Series
is analogous to referencing a column
in the DATA
step.
Index
¶
Every DataFrame
and Series
has an Index
- which are labels on the
rows of the data. SAS does not have an exactly analogous concept. A data set’s
row are essentially unlabeled, other than an implicit integer index that can be
accessed during the DATA
step (_N_
).
In pandas, if no index is specified, an integer index is also used by default
(first row = 0, second row = 1, and so on). While using a labeled Index
or
MultiIndex
can enable sophisticated analyses and is ultimately an important
part of pandas to understand, for this comparison we will essentially ignore the
Index
and just treat the DataFrame
as a collection of columns. Please
see the indexing documentation for much more on how to use an
Index
effectively.
Data Input / Output¶
Constructing a DataFrame from Values¶
A SAS data set can be built from specified values by
placing the data after a datalines
statement and
specifying the column names.
data df;
input x y;
datalines;
1 2
3 4
5 6
;
run;
A pandas DataFrame
can be constructed in many different ways,
but for a small number of values, it is often convenient to specify it as
a python dictionary, where the keys are the column names
and the values are the data.
In [3]: df = pd.DataFrame({
...: 'x': [1, 3, 5],
...: 'y': [2, 4, 6]})
...:
In [4]: df
Out[4]:
x y
0 1 2
1 3 4
2 5 6
Reading External Data¶
Like SAS, pandas provides utilities for reading in data from
many formats. The tips
dataset, found within the pandas
tests (csv)
will be used in many of the following examples.
SAS provides PROC IMPORT
to read csv data into a data set.
proc import datafile='tips.csv' dbms=csv out=tips replace;
getnames=yes;
run;
The pandas method is read_csv()
, which works similarly.
In [5]: url = 'https://raw.github.com/pydata/pandas/master/pandas/tests/data/tips.csv'
In [6]: tips = pd.read_csv(url)
---------------------------------------------------------------------------
URLError Traceback (most recent call last)
<ipython-input-6-eb7031f85b0e> in <module>()
----> 1 tips = pd.read_csv(url)
/build/pandas-8apiR_/pandas-0.17.1/debian/python-pandas/usr/lib/python2.7/dist-packages/pandas/io/parsers.pyc in parser_f(filepath_or_buffer, sep, dialect, compression, doublequote, escapechar, quotechar, quoting, skipinitialspace, lineterminator, header, index_col, names, prefix, skiprows, skipfooter, skip_footer, na_values, true_values, false_values, delimiter, converters, dtype, usecols, engine, delim_whitespace, as_recarray, na_filter, compact_ints, use_unsigned, low_memory, buffer_lines, warn_bad_lines, error_bad_lines, keep_default_na, thousands, comment, decimal, parse_dates, keep_date_col, dayfirst, date_parser, memory_map, float_precision, nrows, iterator, chunksize, verbose, encoding, squeeze, mangle_dupe_cols, tupleize_cols, infer_datetime_format, skip_blank_lines)
496 skip_blank_lines=skip_blank_lines)
497
--> 498 return _read(filepath_or_buffer, kwds)
499
500 parser_f.__name__ = name
/build/pandas-8apiR_/pandas-0.17.1/debian/python-pandas/usr/lib/python2.7/dist-packages/pandas/io/parsers.pyc in _read(filepath_or_buffer, kwds)
260 filepath_or_buffer, _, compression = get_filepath_or_buffer(filepath_or_buffer,
261 encoding,
--> 262 compression=kwds.get('compression', None))
263 kwds['compression'] = inferred_compression if compression == 'infer' else compression
264
/build/pandas-8apiR_/pandas-0.17.1/debian/python-pandas/usr/lib/python2.7/dist-packages/pandas/io/common.pyc in get_filepath_or_buffer(filepath_or_buffer, encoding, compression)
256
257 if _is_url(filepath_or_buffer):
--> 258 req = _urlopen(str(filepath_or_buffer))
259 if compression == 'infer':
260 content_encoding = req.headers.get('Content-Encoding', None)
/usr/lib/python2.7/urllib2.pyc in urlopen(url, data, timeout, cafile, capath, cadefault, context)
152 else:
153 opener = _opener
--> 154 return opener.open(url, data, timeout)
155
156 def install_opener(opener):
/usr/lib/python2.7/urllib2.pyc in open(self, fullurl, data, timeout)
429 req = meth(req)
430
--> 431 response = self._open(req, data)
432
433 # post-process response
/usr/lib/python2.7/urllib2.pyc in _open(self, req, data)
447 protocol = req.get_type()
448 result = self._call_chain(self.handle_open, protocol, protocol +
--> 449 '_open', req)
450 if result:
451 return result
/usr/lib/python2.7/urllib2.pyc in _call_chain(self, chain, kind, meth_name, *args)
407 func = getattr(handler, meth_name)
408
--> 409 result = func(*args)
410 if result is not None:
411 return result
/usr/lib/python2.7/urllib2.pyc in https_open(self, req)
1238 def https_open(self, req):
1239 return self.do_open(httplib.HTTPSConnection, req,
-> 1240 context=self._context)
1241
1242 https_request = AbstractHTTPHandler.do_request_
/usr/lib/python2.7/urllib2.pyc in do_open(self, http_class, req, **http_conn_args)
1195 except socket.error, err: # XXX what error?
1196 h.close()
-> 1197 raise URLError(err)
1198 else:
1199 try:
URLError: <urlopen error [Errno 111] Connection refused>
In [7]: tips.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-7-9b5f9fb19d63> in <module>()
----> 1 tips.head()
NameError: name 'tips' is not defined
Like PROC IMPORT
, read_csv
can take a number of parameters to specify
how the data should be parsed. For example, if the data was instead tab delimited,
and did not have column names, the pandas command would be:
tips = pd.read_csv('tips.csv', sep='\t', header=None)
# alternatively, read_table is an alias to read_csv with tab delimiter
tips = pd.read_table('tips.csv', header=None)
In addition to text/csv, pandas supports a variety of other data formats
such as Excel, HDF5, and SQL databases. These are all read via a pd.read_*
function. See the IO documentation for more details.
Data Operations¶
Operations on Columns¶
In the DATA
step, arbitrary math expressions can
be used on new or existing columns.
data tips;
set tips;
total_bill = total_bill - 2;
new_bill = total_bill / 2;
run;
pandas provides similar vectorized operations by
specifying the individual Series
in the DataFrame
.
New columns can be assigned in the same way.
In [8]: tips['total_bill'] = tips['total_bill'] - 2
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-8-99eac591b314> in <module>()
----> 1 tips['total_bill'] = tips['total_bill'] - 2
NameError: name 'tips' is not defined
In [9]: tips['new_bill'] = tips['total_bill'] / 2.0
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-9-66d9d3f6fc9d> in <module>()
----> 1 tips['new_bill'] = tips['total_bill'] / 2.0
NameError: name 'tips' is not defined
In [10]: tips.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-10-9b5f9fb19d63> in <module>()
----> 1 tips.head()
NameError: name 'tips' is not defined
Filtering¶
Filtering in SAS is done with an if
or where
statement, on one
or more columns.
data tips;
set tips;
if total_bill > 10;
run;
data tips;
set tips;
where total_bill > 10;
/* equivalent in this case - where happens before the
DATA step begins and can also be used in PROC statements */
run;
DataFrames can be filtered in multiple ways; the most intuitive of which is using boolean indexing
In [11]: tips[tips['total_bill'] > 10].head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-11-da383754b0cf> in <module>()
----> 1 tips[tips['total_bill'] > 10].head()
NameError: name 'tips' is not defined
If/Then Logic¶
In SAS, if/then logic can be used to create new columns.
data tips;
set tips;
format bucket $4.;
if total_bill < 10 then bucket = 'low';
else bucket = 'high';
run;
The same operation in pandas can be accomplished using
the where
method from numpy
.
In [12]: tips['bucket'] = np.where(tips['total_bill'] < 10, 'low', 'high')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-12-496f2fc45c1b> in <module>()
----> 1 tips['bucket'] = np.where(tips['total_bill'] < 10, 'low', 'high')
NameError: name 'tips' is not defined
In [13]: tips.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-13-9b5f9fb19d63> in <module>()
----> 1 tips.head()
NameError: name 'tips' is not defined
Date Functionality¶
SAS provides a variety of functions to do operations on date/datetime columns.
data tips;
set tips;
format date1 date2 date1_plusmonth mmddyy10.;
date1 = mdy(1, 15, 2013);
date2 = mdy(2, 15, 2015);
date1_year = year(date1);
date2_month = month(date2);
* shift date to begninning of next interval;
date1_next = intnx('MONTH', date1, 1);
* count intervals between dates;
months_between = intck('MONTH', date1, date2);
run;
The equivalent pandas operations are shown below. In addition to these functions pandas supports other Time Series features not available in Base SAS (such as resampling and and custom offets) - see the timeseries documentation for more details.
In [14]: tips['date1'] = pd.Timestamp('2013-01-15')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-14-b3452c22a4d8> in <module>()
----> 1 tips['date1'] = pd.Timestamp('2013-01-15')
NameError: name 'tips' is not defined
In [15]: tips['date2'] = pd.Timestamp('2015-02-15')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-15-7cc1a1a8c40a> in <module>()
----> 1 tips['date2'] = pd.Timestamp('2015-02-15')
NameError: name 'tips' is not defined
In [16]: tips['date1_year'] = tips['date1'].dt.year
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-16-cfc1ce15858c> in <module>()
----> 1 tips['date1_year'] = tips['date1'].dt.year
NameError: name 'tips' is not defined
In [17]: tips['date2_month'] = tips['date2'].dt.month
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-17-3f13318c9e1e> in <module>()
----> 1 tips['date2_month'] = tips['date2'].dt.month
NameError: name 'tips' is not defined
In [18]: tips['date1_next'] = tips['date1'] + pd.offsets.MonthBegin()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-18-ec7a37674786> in <module>()
----> 1 tips['date1_next'] = tips['date1'] + pd.offsets.MonthBegin()
NameError: name 'tips' is not defined
In [19]: tips['months_between'] = (tips['date2'].dt.to_period('M') -
....: tips['date1'].dt.to_period('M'))
....:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-19-fa3eb7557d9c> in <module>()
----> 1 tips['months_between'] = (tips['date2'].dt.to_period('M') -
2 tips['date1'].dt.to_period('M'))
NameError: name 'tips' is not defined
In [20]: tips[['date1','date2','date1_year','date2_month',
....: 'date1_next','months_between']].head()
....:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-20-63ecc82db826> in <module>()
----> 1 tips[['date1','date2','date1_year','date2_month',
2 'date1_next','months_between']].head()
NameError: name 'tips' is not defined
Selection of Columns¶
SAS provides keywords in the DATA
step to select,
drop, and rename columns.
data tips;
set tips;
keep sex total_bill tip;
run;
data tips;
set tips;
drop sex;
run;
data tips;
set tips;
rename total_bill=total_bill_2;
run;
The same operations are expressed in pandas below.
# keep
In [21]: tips[['sex', 'total_bill', 'tip']].head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-21-5d3e68507f85> in <module>()
----> 1 tips[['sex', 'total_bill', 'tip']].head()
NameError: name 'tips' is not defined
# drop
In [22]: tips.drop('sex', axis=1).head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-22-92fb22b07591> in <module>()
----> 1 tips.drop('sex', axis=1).head()
NameError: name 'tips' is not defined
# rename
In [23]: tips.rename(columns={'total_bill':'total_bill_2'}).head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-fc43878ab5b8> in <module>()
----> 1 tips.rename(columns={'total_bill':'total_bill_2'}).head()
NameError: name 'tips' is not defined
Sorting by Values¶
Sorting in SAS is accomplished via PROC SORT
proc sort data=tips;
by sex total_bill;
run;
pandas objects have a sort_values()
method, which
takes a list of columnns to sort by.
In [24]: tips = tips.sort_values(['sex', 'total_bill'])
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-24-5de00c1749a0> in <module>()
----> 1 tips = tips.sort_values(['sex', 'total_bill'])
NameError: name 'tips' is not defined
In [25]: tips.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-9b5f9fb19d63> in <module>()
----> 1 tips.head()
NameError: name 'tips' is not defined
Merging¶
The following tables will be used in the merge examples
In [26]: df1 = pd.DataFrame({'key': ['A', 'B', 'C', 'D'],
....: 'value': np.random.randn(4)})
....:
In [27]: df1
Out[27]:
key value
0 A -0.857326
1 B 1.075416
2 C 0.371727
3 D 1.065735
In [28]: df2 = pd.DataFrame({'key': ['B', 'D', 'D', 'E'],
....: 'value': np.random.randn(4)})
....:
In [29]: df2
Out[29]:
key value
0 B -0.227314
1 D 2.102726
2 D -0.092796
3 E 0.094694
In SAS, data must be explicitly sorted before merging. Different
types of joins are accomplished using the in=
dummy
variables to track whether a match was found in one or both
input frames.
proc sort data=df1;
by key;
run;
proc sort data=df2;
by key;
run;
data left_join inner_join right_join outer_join;
merge df1(in=a) df2(in=b);
if a and b then output inner_join;
if a then output left_join;
if b then output right_join;
if a or b then output outer_join;
run;
pandas DataFrames have a merge()
method, which provides
similar functionality. Note that the data does not have
to be sorted ahead of time, and different join
types are accomplished via the how
keyword.
In [30]: inner_join = df1.merge(df2, on=['key'], how='inner')
In [31]: inner_join
Out[31]:
key value_x value_y
0 B 1.075416 -0.227314
1 D 1.065735 2.102726
2 D 1.065735 -0.092796
In [32]: left_join = df1.merge(df2, on=['key'], how='left')
In [33]: left_join
Out[33]:
key value_x value_y
0 A -0.857326 NaN
1 B 1.075416 -0.227314
2 C 0.371727 NaN
3 D 1.065735 2.102726
4 D 1.065735 -0.092796
In [34]: right_join = df1.merge(df2, on=['key'], how='right')
In [35]: right_join
Out[35]:
key value_x value_y
0 B 1.075416 -0.227314
1 D 1.065735 2.102726
2 D 1.065735 -0.092796
3 E NaN 0.094694
In [36]: outer_join = df1.merge(df2, on=['key'], how='outer')
In [37]: outer_join
Out[37]:
key value_x value_y
0 A -0.857326 NaN
1 B 1.075416 -0.227314
2 C 0.371727 NaN
3 D 1.065735 2.102726
4 D 1.065735 -0.092796
5 E NaN 0.094694
Missing Data¶
Like SAS, pandas has a representation for missing data - which is the
special float value NaN
(not a number). Many of the semantics
are the same, for example missing data propagates through numeric
operations, and is ignored by default for aggregations.
In [38]: outer_join
Out[38]:
key value_x value_y
0 A -0.857326 NaN
1 B 1.075416 -0.227314
2 C 0.371727 NaN
3 D 1.065735 2.102726
4 D 1.065735 -0.092796
5 E NaN 0.094694
In [39]: outer_join['value_x'] + outer_join['value_y']
Out[39]:
0 NaN
1 0.848102
2 NaN
3 3.168461
4 0.972939
5 NaN
dtype: float64
In [40]: outer_join['value_x'].sum()
Out[40]: 2.7212865354426201
One difference is that missing data cannot be compared to its sentinel value. For example, in SAS you could do this to filter missing values.
data outer_join_nulls;
set outer_join;
if value_x = .;
run;
data outer_join_no_nulls;
set outer_join;
if value_x ^= .;
run;
Which doesn’t work in in pandas. Instead, the pd.isnull
or pd.notnull
functions
should be used for comparisons.
In [41]: outer_join[pd.isnull(outer_join['value_x'])]
Out[41]:
key value_x value_y
5 E NaN 0.094694
In [42]: outer_join[pd.notnull(outer_join['value_x'])]
Out[42]:
key value_x value_y
0 A -0.857326 NaN
1 B 1.075416 -0.227314
2 C 0.371727 NaN
3 D 1.065735 2.102726
4 D 1.065735 -0.092796
pandas also provides a variety of methods to work with missing data - some of which would be challenging to express in SAS. For example, there are methods to drop all rows with any missing values, replacing missing values with a specified value, like the mean, or forward filling from previous rows. See the missing data documentation for more.
In [43]: outer_join.dropna()
Out[43]:
key value_x value_y
1 B 1.075416 -0.227314
3 D 1.065735 2.102726
4 D 1.065735 -0.092796
In [44]: outer_join.fillna(method='ffill')
Out[44]:
key value_x value_y
0 A -0.857326 NaN
1 B 1.075416 -0.227314
2 C 0.371727 -0.227314
3 D 1.065735 2.102726
4 D 1.065735 -0.092796
5 E 1.065735 0.094694
In [45]: outer_join['value_x'].fillna(outer_join['value_x'].mean())
Out[45]:
0 -0.857326
1 1.075416
2 0.371727
3 1.065735
4 1.065735
5 0.544257
Name: value_x, dtype: float64
GroupBy¶
Aggregation¶
SAS’s PROC SUMMARY can be used to group by one or more key variables and compute aggregations on numeric columns.
proc summary data=tips nway;
class sex smoker;
var total_bill tip;
output out=tips_summed sum=;
run;
pandas provides a flexible groupby
mechanism that
allows similar aggregations. See the groupby documentation
for more details and examples.
In [46]: tips_summed = tips.groupby(['sex', 'smoker'])['total_bill', 'tip'].sum()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-46-28c41a97a164> in <module>()
----> 1 tips_summed = tips.groupby(['sex', 'smoker'])['total_bill', 'tip'].sum()
NameError: name 'tips' is not defined
In [47]: tips_summed.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-47-ea803183022e> in <module>()
----> 1 tips_summed.head()
NameError: name 'tips_summed' is not defined
Transformation¶
In SAS, if the group aggregations need to be used with the original frame, it must be merged back together. For example, to subtract the mean for each observation by smoker group.
proc summary data=tips missing nway;
class smoker;
var total_bill;
output out=smoker_means mean(total_bill)=group_bill;
run;
proc sort data=tips;
by smoker;
run;
data tips;
merge tips(in=a) smoker_means(in=b);
by smoker;
adj_total_bill = total_bill - group_bill;
if a and b;
run;
pandas groubpy
provides a transform
mechanism that allows
these type of operations to be succinctly expressed in one
operation.
In [48]: gb = tips.groupby('smoker')['total_bill']
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-48-edc8dc704df9> in <module>()
----> 1 gb = tips.groupby('smoker')['total_bill']
NameError: name 'tips' is not defined
In [49]: tips['adj_total_bill'] = tips['total_bill'] - gb.transform('mean')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-49-a4e612bdef86> in <module>()
----> 1 tips['adj_total_bill'] = tips['total_bill'] - gb.transform('mean')
NameError: name 'tips' is not defined
In [50]: tips.head()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-50-9b5f9fb19d63> in <module>()
----> 1 tips.head()
NameError: name 'tips' is not defined
By Group Processing¶
In addition to aggregation, pandas groupby
can be used to
replicate most other by group processing from SAS. For example,
this DATA
step reads the data by sex/smoker group and filters to
the first entry for each.
proc sort data=tips;
by sex smoker;
run;
data tips_first;
set tips;
by sex smoker;
if FIRST.sex or FIRST.smoker then output;
run;
In pandas this would be written as:
In [51]: tips.groupby(['sex','smoker']).first()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-51-ec794b6abf5a> in <module>()
----> 1 tips.groupby(['sex','smoker']).first()
NameError: name 'tips' is not defined
Other Considerations¶
Disk vs Memory¶
pandas operates exclusively in memory, where a SAS data set exists on disk. This means that the size of data able to be loaded in pandas is limited by your machine’s memory, but also that the operations on that data may be faster.
If out of core processing is needed, one possibility is the
dask.dataframe
library (currently in development) which
provides a subset of pandas functionality for an on-disk DataFrame
Data Interop¶
pandas provides a read_sas()
method that can read SAS data saved in
the XPORT format. The ability to read SAS’s binary format is planned for a
future release.
libname xportout xport 'transport-file.xpt';
data xportout.tips;
set tips(rename=(total_bill=tbill));
* xport variable names limited to 6 characters;
run;
df = pd.read_sas('transport-file.xpt')
XPORT is a relatively limited format and the parsing of it is not as optimized as some of the other pandas readers. An alternative way to interop data between SAS and pandas is to serialize to csv.
# version 0.17, 10M rows
In [8]: %time df = pd.read_sas('big.xpt')
Wall time: 14.6 s
In [9]: %time df = pd.read_csv('big.csv')
Wall time: 4.86 s