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]: importpandasaspdIn [2]: importnumpyasnp
Data structures
General terminology translation
pandas
SAS
DataFrame
data set
column
variable
row
observation
groupby
BY-group
NaN
.
DataFrame
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.
Series
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
rows 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.
Copies vs. in place operations
Most pandas operations return copies of the Series/DataFrame. To make the changes “stick”,
you’ll need to either assign to a new variable:
sorted_df=df.sort_values("col1")
or overwrite the original one:
df=df.sort_values("col1")
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;
inputx 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 [1]: df=pd.DataFrame({"x":[1,3,5],"y":[2,4,6]})In [2]: dfOut[2]: x y0 1 21 3 42 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 PROCIMPORT to read csv data into a data set.
Similarly in pandas, the opposite of read_csv is to_csv(),
and other data formats follow a similar api.
tips.
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 vectorized operations by specifying the individual Series in the
DataFrame. New columns can be assigned in the same way. The DataFrame.drop() method drops
a column from the DataFrame.
In [1]: tips["total_bill"]=tips["total_bill"]-2In [2]: tips["new_bill"]=tips["total_bill"]/2In [3]: tipsOut[3]: total_bill tip sex smoker day time size new_bill0 14.99 1.01 Female No Sun Dinner 2 7.4951 8.34 1.66 Male No Sun Dinner 3 4.1702 19.01 3.50 Male No Sun Dinner 3 9.5053 21.68 3.31 Male No Sun Dinner 2 10.840
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
.
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 < 10then bucket = 'low';
else bucket = 'high';run;
The same operation in pandas can be accomplished using
the where method from numpy.
In [1]: tips
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 beginning of next interval;
date1_next = intnx('MONTH', date1, 1);
* count intervals between dates;
months_between = intck('MONTH', date1, date2);run;
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.
SAS determines the length of a character string with the
LENGTHN
and LENGTHC
functions. LENGTHN excludes trailing blanks and LENGTHC includes trailing blanks.
data _null_;
set tips;
put(LENGTHN(time));
put(LENGTHC(time));run;
You can find the length of a character string with Series.str.len().
In Python 3, all strings are Unicode strings. len includes trailing blanks.
Use len and rstrip to exclude trailing blanks.
SAS determines the position of a character in a string with the
FINDW function.
FINDW takes the string defined by the first argument and searches for the first position of the substring
you supply as the second argument.
data _null_;
set tips;
put(FINDW(sex,'ale'));run;
You can find the position of a character in a column of strings with the Series.str.find()
method. find searches for the first position of the substring. If the substring is found, the
method returns its position. If not found, it returns . Keep in mind that Python indexes are
zero-based.
Extracting substring by position
SAS extracts a substring from a string based on its position with the
SUBSTR function.
data _null_;
set tips;
put(substr(sex,1,1));run;
With pandas you can use [] notation to extract a substring
from a string by position locations. Keep in mind that Python
indexes are zero-based.
In [1]: tips["sex"].
Extracting nth word
The SAS SCAN
function returns the nth word from a string. The first argument is the string you want to parse and the
second argument specifies which word you want to extract.
data firstlast;
input String $60.;
First_Name = scan(string, 1);
Last_Name = scan(string, -1);
datalines2;
John Smith;
Jane Cook;
;;;run;
The simplest way to extract words in pandas is to split the strings by spaces, then reference the
word by index. Note there are more powerful approaches should you need them.
The following tables will be used in the merge examples:
In [1]: df1=pd.DataFrame({"key":["A","B","C","D"],"value":np.random.randn(4)})In [2]: df1Out[2]: key value0 A 0.4691121 B -0.2828632 C -1.5090593 D -1.135632In [3]: df2=pd.DataFrame({"key":["B","D","D","E"],"value":np.random.randn(4)})In [4]: df2Out[4]: key value0 B 1.2121121 D -0.1732152 D 0.1192093 E -1.044236
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;
bykey;run;proc sort data=df2;
bykey;run;data left_join inner_join right_join outer_join;
merge df1(in=a) df2(in=b);
if a and b thenoutput inner_join;
if a thenoutput left_join;
if b thenoutput right_join;
if a or b thenoutput outer_join;run;
pandas DataFrames have a merge() method, which provides similar functionality. The
data does not have to be sorted ahead of time, and different join types are accomplished via the
how keyword.
In [1]: inner_join=df1.merge(df2,on=["key"],how="inner")In [2]: inner_joinOut[2]: key value_x value_y0 B -0.282863 1.2121121 D -1.135632 -0.1732152 D -1.135632 0.119209In [3]: left_join=df1.merge(df2,on=
Missing data
Both pandas and SAS have a representation for missing data.
pandas represents missing data with 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 [1]: outer_joinOut[1]: key value_x value_y0 A 0.469112 NaN1 B -0.282863 1.2121122 C -1.509059 NaN3 D -1.135632 -0.1732154 D -1.135632 0.1192095 E NaN -1.044236In [2]: outer_join["value_x"]+outer_join["value_y"]Out[2]: 0 NaN1 0.9292492 NaN3 -1.3088474 -1.0164245 NaNdtype: float64In [3]: outer_join["value_x"].sum()Out[3]: -3.5940742896293765
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;
In [1]: outer_join[outer_join["value_x"].isna()]Out[1]: key value_x value_y5 E NaN -1.044236In [2]: outer_join[outer_join["value_x"].notna()]Out[2]: key value_x value_y0 A 0.469112 NaN1 B -0.282863 1.2121122 C -1.509059 NaN3 D -1.135632 -0.1732154 D -1.135632 0.119209
In [3]: outer_join.dropna()Out[3]: key value_x value_y1 B -0.282863 1.2121123 D -1.135632 -0.1732154 D -1.135632 0.119209
Forward fill from previous rows
In [4]: outer_join.ffill()Out[4]: key value_x value_y0 A 0.469112 NaN1 B -0.282863 1.2121122 C -1.509059 1.2121123 D -1.135632 -0.1732154 D -1.135632 0.1192095 E -1.135632 -1.044236
SAS’s PROCSUMMARY 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;
outputout=tips_summed sum=;run;
pandas provides a flexible groupby mechanism that allows similar aggregations. See the
groupby documentation for more details and examples.
In [1]: tips_summed=tips.groupby(["sex","smoker"])[["total_bill","tip"]].sum()In [2]: tips_summedOut[2]: total_bill tipsex smoker Female No 869.68 149.77 Yes 527.27 96.74Male No 1725.75 302.00 Yes 1217.07 183.07
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;
outputout=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;
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 thenoutput;run;
In pandas this would be written as:
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 or SAS7BDAT binary format.
libname xportout xport 'transport-file.xpt';data xportout.tips;
set tips(rename=(total_bill=tbill));
* xport variable names limited to 6 characters;run;
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 rowsIn [8]: %time df = pd.read_sas('big.xpt')
Wall time: 14.6 sIn [9]: %time df = pd.read_csv('big.csv')
Wall time: 4.86 s
In [3]: url=( ...: "https://raw.githubusercontent.com/pandas-dev/" ...: "pandas/main/pandas/tests/io/data/csv/tips.csv" ...: ) ...: In [4]: tips=pd.read_csv(url)In [5]: tipsOut[5]: total_bill tip sex smoker day time size0 16.99 1.01 Female No Sun Dinner 21 10.34 1.66 Male No Sun Dinner 32 21.01 3.50 Male No Sun Dinner 33 23.68 3.31 Male No Sun Dinner 24 24.59 3.61 Female No Sun Dinner 4.. ... ... ... ... ... ... ...239 29.03 5.92 Male No Sat Dinner 3240 27.18 2.00 Female Yes Sat Dinner 2241 22.67 2.00 Male Yes Sat Dinner 2242 17.82 1.75 Male No Sat Dinner 2243 18.78 3.00 Female No Thur Dinner 2[244 rows x 7 columns]
Like PROCIMPORT, 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 delimitertips=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.
1 10.34 1.66 Male No Sun Dinner 3
2 21.01 3.50 Male No Sun Dinner 3
3 23.68 3.31 Male No Sun Dinner 2
4 24.59 3.61 Female No Sun Dinner 4
The equivalent in SAS would be:
proc print data=df(obs=5);run;
to_csv
(
"tips2.csv"
)
4 22.59 3.61 Female No Sun Dinner 4 11.295
.. ... ... ... ... ... ... ... ...
239 27.03 5.92 Male No Sat Dinner 3 13.515
240 25.18 2.00 Female Yes Sat Dinner 2 12.590
241 20.67 2.00 Male Yes Sat Dinner 2 10.335
242 15.82 1.75 Male No Sat Dinner 2 7.910
243 16.78 3.00 Female No Thur Dinner 2 8.390
[244 rows x 8 columns]
In [4]:
tips
=
tips
.
drop
(
"new_bill"
,
axis
=
1
)
boolean indexing
In [1]: tips[tips["total_bill"]>10]Out[1]: total_bill tip sex smoker day time size0 14.99 1.01 Female No Sun Dinner 22 19.01 3.50 Male No Sun Dinner 33 21.68 3.31 Male No Sun Dinner 24 22.59 3.61 Female No Sun Dinner 45 23.29 4.71 Male No Sun Dinner 4.. ... ... ... ... ... ... ...239 27.03 5.92 Male No Sat Dinner 3240 25.18 2.00 Female Yes Sat Dinner 2241 20.67 2.00 Male Yes Sat Dinner 2242 15.82 1.75 Male No Sat Dinner 2243 16.78 3.00 Female No Thur Dinner 2[204 rows x 7 columns]
The above statement is simply passing a Series of True/False objects to the DataFrame,
returning all rows with True.
In [2]: is_dinner=tips["time"]=="Dinner"In [3]: is_dinnerOut[3]: 0 True1 True2 True3 True4 True ... 239 True240 True241 True242 True243 TrueName: time, Length: 244, dtype: boolIn [4]: is_dinner.value_counts()Out[4]: timeTrue 176False 68Name: count, dtype: int64In [5]: tips[is_dinner]Out[5]: total_bill tip sex smoker day time size0 14.99 1.01 Female No Sun Dinner 21 8.34 1.66 Male No Sun Dinner 32 19.01 3.50 Male No Sun Dinner 33 21.68 3.31 Male No Sun Dinner 24 22.59 3.61 Female No Sun Dinner 4.. ... ... ... ... ... ... ...239 27.03 5.92 Male No Sat Dinner 3240 25.18 2.00 Female Yes Sat Dinner 2241 20.67 2.00 Male Yes Sat Dinner 2242 15.82 1.75 Male No Sat Dinner 2243 16.78 3.00 Female No Thur Dinner 2[176 rows x 7 columns]
[
"bucket"
]
=
np
.
where
(
tips
[
"total_bill"
]
<
10
,
"low"
,
"high"
)
In [2]:
tips
Out[2]:
total_bill tip sex smoker day time size bucket
0 14.99 1.01 Female No Sun Dinner 2 high
1 8.34 1.66 Male No Sun Dinner 3 low
2 19.01 3.50 Male No Sun Dinner 3 high
3 21.68 3.31 Male No Sun Dinner 2 high
4 22.59 3.61 Female No Sun Dinner 4 high
.. ... ... ... ... ... ... ... ...
239 27.03 5.92 Male No Sat Dinner 3 high
240 25.18 2.00 Female Yes Sat Dinner 2 high
241 20.67 2.00 Male Yes Sat Dinner 2 high
242 15.82 1.75 Male No Sat Dinner 2 high
243 16.78 3.00 Female No Thur Dinner 2 high
[244 rows x 8 columns]
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 custom offsets) -
see the timeseries documentation for more details.
In [1]: tips[["sex","total_bill","tip"]]Out[1]: sex total_bill tip0 Female 14.99 1.011 Male 8.34 1.662 Male 19.01 3.503 Male 21.68 3.314 Female 22.59 3.61.. ... ... ...239 Male 27.03 5.92240 Female 25.18 2.00241 Male 20.67 2.00242 Male 15.82 1.75243 Female 16.78 3.00[244 rows x 3 columns]
Drop a column
In [2]: tips.drop("sex",axis=1)Out[2]: total_bill tip smoker day time size0 14.99 1.01 No Sun Dinner 21 8.34 1.66 No Sun Dinner 32 19.01 3.50 No Sun Dinner 33 21.68 3.31 No Sun Dinner 24 22.59 3.61 No Sun Dinner 4.. ... ... ... ... ... ...239 27.03 5.92 No Sat Dinner 3240 25.18 2.00 Yes Sat Dinner 2241 20.67 2.00 Yes Sat Dinner 2242 15.82 1.75 No Sat Dinner 2243 16.78 3.00 No Thur Dinner 2[244 rows x 6 columns]
Rename a column
In [3]: tips.rename(columns={"total_bill":"total_bill_2"})Out[3]: total_bill_2 tip sex smoker day time size0 14.99 1.01 Female No Sun Dinner 21 8.34 1.66 Male No Sun Dinner 32 19.01 3.50 Male No Sun Dinner 33 21.68 3.31 Male No Sun Dinner 24 22.59 3.61 Female No Sun Dinner 4.. ... ... ... ... ... ... ...239 27.03 5.92 Male No Sat Dinner 3240 25.18 2.00 Female Yes Sat Dinner 2241 20.67 2.00 Male Yes Sat Dinner 2242 15.82 1.75 Male No Sat Dinner 2243 16.78 3.00 Female No Thur Dinner 2[244 rows x 7 columns]
In [1]: firstlast=pd.DataFrame({"string":["John Smith","Jane Cook"]})In [2]: firstlast["upper"]=firstlast["string"].str.upper()In [3]: firstlast["lower"]=firstlast["string"].str.lower()In [4]: firstlast["title"]=firstlast["string"].str.title()In [5]: firstlastOut[5]: string upper lower title0 John Smith JOHN SMITH john smith John Smith1 Jane Cook JANE COOK jane cook Jane Cook
[
"key"
],
how
=
"left"
)
In [4]:
left_join
Out[4]:
key value_x value_y
0 A 0.469112 NaN
1 B -0.282863 1.212112
2 C -1.509059 NaN
3 D -1.135632 -0.173215
4 D -1.135632 0.119209
In [5]:
right_join
=
df1
.
merge
(
df2
,
on
=
[
"key"
],
how
=
"right"
)
In [6]:
right_join
Out[6]:
key value_x value_y
0 B -0.282863 1.212112
1 D -1.135632 -0.173215
2 D -1.135632 0.119209
3 E NaN -1.044236
In [7]:
outer_join
=
df1
.
merge
(
df2
,
on
=
[
"key"
],
how
=
"outer"
)
In [8]:
outer_join
Out[8]:
key value_x value_y
0 A 0.469112 NaN
1 B -0.282863 1.212112
2 C -1.509059 NaN
3 D -1.135632 -0.173215
4 D -1.135632 0.119209
5 E NaN -1.044236
pandas provides a Transformation mechanism that allows these type of operations to be
succinctly expressed in one operation.
In [1]: gb=tips.groupby("smoker")["total_bill"]In [2]: tips["adj_total_bill"]=tips["total_bill"]-gb.transform("mean")In [3]: tipsOut[3]: total_bill tip sex smoker day time size adj_total_bill67 1.07 1.00 Female Yes Sat Dinner 1 -17.68634492 3.75 1.00 Female Yes Fri Dinner 2 -15.006344111 5.25 1.00 Female No Sat Dinner 1 -11.938278145 6.35 1.50 Female No Thur Lunch 2 -10.838278135 6.51 1.25 Female No Thur Lunch 2 -10.678278.. ... ... ... ... ... ... ... ...182 43.35 3.50 Male Yes Sun Dinner 3 24.593656156 46.17 5.00 Male No Sun Dinner 6 28.98172259 46.27 6.73 Male No Sat Dinner 4 29.081722212 46.33 9.00 Male No Sat Dinner 4 29.141722170 48.81 10.00 Male Yes Sat Dinner 3 30.053656[244 rows x 8 columns]
In [4]: tips.groupby(["sex","smoker"]).first()Out[4]: total_bill tip day time size adj_total_billsex smoker Female No 5.25 1.00 Sat Dinner 1 -11.938278 Yes 1.07 1.00 Sat Dinner 1 -17.686344Male No 5.51 2.00 Thur Lunch 2 -11.678278 Yes 5.25 5.15 Sun Dinner 2 -13.506344