与SAS的比较#

对于来自的潜在用户 SAS 本页面旨在演示如何在大Pandas身上执行不同的SAS操作。

如果你是Pandas的新手,你可能想先通读一下 10 Minutes to pandas 让你自己熟悉类库。

按照惯例,我们进口Pandas和NumPy如下:

In [1]: import pandas as pd

In [2]: import numpy as np

数据结构#

通用术语翻译#

Pandas

SAS

DataFrame

数据集

立柱

变量

观察

GroupBy

按组

NaN

.

DataFrame#

A DataFrame 类似于SAS数据集--一种带有标签列的二维数据源,可以是不同类型的列。如本文中所示,几乎任何可应用于使用SAS的数据集的操作 DATA 一步,也可以在大Pandas身上完成。

Series#

A Series 是表示 DataFrame 。对于单个列,SAS没有单独的数据结构,但一般来说,使用 Series 类似于引用 DATA 一步。

Index#

每个 DataFrameSeries vbl.有一个 Index -这些标签位于 rows 数据的一部分。SA没有一个完全类似的概念。数据集的行基本上是未标记的,除了可以在 DATA 步骤 (_N_ )。

在PANDA中,如果未指定索引,则默认情况下也使用整数索引(第一行=0,第二行=1,依此类推)。同时使用带标签的 IndexMultiIndex 可以进行复杂的分析,这最终是Pandas理解的重要部分,对于这种比较,我们基本上将忽略 Index 只需治疗 DataFrame 作为列的集合。请参阅 indexing documentation 有关如何使用 Index 有效地。

复印件与就地操作#

大多数大Pandas的操作都会返回 Series/DataFrame 。要使更改“生效”,您需要为一个新变量赋值:

sorted_df = df.sort_values("col1")

或覆盖原始文件:

df = df.sort_values("col1")

备注

您将看到一个 inplace=True 某些方法可用的关键字参数:

df.sort_values("col1", inplace=True)

它的使用是不鼓励的。 More information.

数据输入/输出#

从值构造DataFrame#

通过将数据放在 datalines 语句并指定列名。

data df;
    input x y;
    datalines;
    1 2
    3 4
    5 6
    ;
run;

一只Pandas DataFrame 可以用许多不同的方式构造,但对于少量的值,通常可以将其指定为一个Python字典,其中键是列名,值是数据。

In [1]: df = pd.DataFrame({"x": [1, 3, 5], "y": [2, 4, 6]})

In [2]: df
Out[2]: 
   x  y
0  1  2
1  3  4
2  5  6

正在读取外部数据#

与SAS一样,Pandas也提供了从多种格式读取数据的实用程序。这个 tips 数据集,在Pandas测试中找到 (csv )将在下面的许多示例中使用。

SAS提供 PROC IMPORT 将CSV数据读入数据集中。

proc import datafile='tips.csv' dbms=csv out=tips replace;
    getnames=yes;
run;

Pandas的方法是 read_csv() ,它的工作原理类似。

In [3]: url = (
   ...:     "https://raw.github.com/pandas-dev/"
   ...:     "pandas/main/pandas/tests/io/data/csv/tips.csv"
   ...: )
   ...: 

In [4]: tips = pd.read_csv(url)

In [5]: tips
Out[5]: 
     total_bill   tip     sex smoker   day    time  size
0         16.99  1.01  Female     No   Sun  Dinner     2
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
..          ...   ...     ...    ...   ...     ...   ...
239       29.03  5.92    Male     No   Sat  Dinner     3
240       27.18  2.00  Female    Yes   Sat  Dinner     2
241       22.67  2.00    Male    Yes   Sat  Dinner     2
242       17.82  1.75    Male     No   Sat  Dinner     2
243       18.78  3.00  Female     No  Thur  Dinner     2

[244 rows x 7 columns]

喜欢 PROC IMPORTread_csv 可以采用多个参数来指定应如何分析数据。例如,如果数据改用制表符分隔,并且没有列名,则PANDAS命令将为:

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)

除了文本/CSV之外,PANDA还支持各种其他数据格式,如Excel、HDF5和SQL数据库。这些都是通过 pd.read_* 功能。请参阅 IO documentation 了解更多详细信息。

限制产量#

默认情况下,Pandas将截断大型 DataFrame 以显示第一行和最后一行。这可以通过以下方式覆盖 changing the pandas options ,或使用 DataFrame.head()DataFrame.tail()

In [1]: tips.head(5)
Out[1]: 
   total_bill   tip     sex smoker  day    time  size
0       16.99  1.01  Female     No  Sun  Dinner     2
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

SAS中的等价物为:

proc print data=df(obs=5);
run;

正在导出数据#

与之相反的 PROC IMPORT 在SAS中是 PROC EXPORT

proc export data=tips outfile='tips2.csv' dbms=csv;
run;

同样,在大Pandas身上, read_csvto_csv() 和其他数据格式遵循类似的API。

tips.to_csv("tips2.csv")

数据操作#

列上的操作#

DATA 步骤中,可以在新列或现有列上使用任意数学表达式。

data tips;
    set tips;
    total_bill = total_bill - 2;
    new_bill = total_bill / 2;
run;

Pandas通过指定个体来提供矢量化操作 SeriesDataFrame 。可以用相同的方式分配新列。这个 DataFrame.drop() 方法将一列从 DataFrame

In [1]: tips["total_bill"] = tips["total_bill"] - 2

In [2]: tips["new_bill"] = tips["total_bill"] / 2

In [3]: tips
Out[3]: 
     total_bill   tip     sex smoker   day    time  size  new_bill
0         14.99  1.01  Female     No   Sun  Dinner     2     7.495
1          8.34  1.66    Male     No   Sun  Dinner     3     4.170
2         19.01  3.50    Male     No   Sun  Dinner     3     9.505
3         21.68  3.31    Male     No   Sun  Dinner     2    10.840
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)

过滤#

在SAS中进行筛选是使用 ifwhere 语句,在一列或多列上。

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;

可以通过多种方式过滤DataFrame;其中最直观的是使用 boolean indexing

In [1]: tips[tips["total_bill"] > 10]
Out[1]: 
     total_bill   tip     sex smoker   day    time  size
0         14.99  1.01  Female     No   Sun  Dinner     2
2         19.01  3.50    Male     No   Sun  Dinner     3
3         21.68  3.31    Male     No   Sun  Dinner     2
4         22.59  3.61  Female     No   Sun  Dinner     4
5         23.29  4.71    Male     No   Sun  Dinner     4
..          ...   ...     ...    ...   ...     ...   ...
239       27.03  5.92    Male     No   Sat  Dinner     3
240       25.18  2.00  Female    Yes   Sat  Dinner     2
241       20.67  2.00    Male    Yes   Sat  Dinner     2
242       15.82  1.75    Male     No   Sat  Dinner     2
243       16.78  3.00  Female     No  Thur  Dinner     2

[204 rows x 7 columns]

上面的语句只是将一个 Series of True/False 对象绑定到DataFrame,并使用 True

In [1]: is_dinner = tips["time"] == "Dinner"

In [2]: is_dinner
Out[2]: 
0      True
1      True
2      True
3      True
4      True
       ... 
239    True
240    True
241    True
242    True
243    True
Name: time, Length: 244, dtype: bool

In [3]: is_dinner.value_counts()
Out[3]: 
True     176
False     68
Name: time, dtype: int64

In [4]: tips[is_dinner]
Out[4]: 
     total_bill   tip     sex smoker   day    time  size
0         14.99  1.01  Female     No   Sun  Dinner     2
1          8.34  1.66    Male     No   Sun  Dinner     3
2         19.01  3.50    Male     No   Sun  Dinner     3
3         21.68  3.31    Male     No   Sun  Dinner     2
4         22.59  3.61  Female     No   Sun  Dinner     4
..          ...   ...     ...    ...   ...     ...   ...
239       27.03  5.92    Male     No   Sat  Dinner     3
240       25.18  2.00  Female    Yes   Sat  Dinner     2
241       20.67  2.00    Male    Yes   Sat  Dinner     2
242       15.82  1.75    Male     No   Sat  Dinner     2
243       16.78  3.00  Female     No  Thur  Dinner     2

[176 rows x 7 columns]

IF/THEN逻辑#

在SAS中,IF/THEN逻辑可用于创建新列。

data tips;
    set tips;
    format bucket $4.;

    if total_bill < 10 then bucket = 'low';
    else bucket = 'high';
run;

在Pandas身上也可以使用 where 方法来自 numpy

In [1]: tips["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]

日期功能#

SAS提供了各种函数来对日期/日期时间列执行操作。

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;

等同的大Pandas手术如下所示。除了这些功能外,Pandas还支持基本SA中没有的其他时间序列功能(如重采样和自定义偏移量)-请参阅 timeseries documentation 了解更多详细信息。

In [1]: tips["date1"] = pd.Timestamp("2013-01-15")

In [2]: tips["date2"] = pd.Timestamp("2015-02-15")

In [3]: tips["date1_year"] = tips["date1"].dt.year

In [4]: tips["date2_month"] = tips["date2"].dt.month

In [5]: tips["date1_next"] = tips["date1"] + pd.offsets.MonthBegin()

In [6]: tips["months_between"] = tips["date2"].dt.to_period("M") - tips[
   ...:     "date1"
   ...: ].dt.to_period("M")
   ...: 

In [7]: tips[
   ...:     ["date1", "date2", "date1_year", "date2_month", "date1_next", "months_between"]
   ...: ]
   ...: 
Out[7]: 
         date1      date2  date1_year  date2_month date1_next    months_between
0   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
1   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
2   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
3   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
4   2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
..         ...        ...         ...          ...        ...               ...
239 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
240 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
241 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
242 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>
243 2013-01-15 2015-02-15        2013            2 2013-02-01  <25 * MonthEnds>

[244 rows x 6 columns]

柱子的选择#

SAS在中提供关键字 DATA 选择、删除和重命名列的步骤。

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;

同样的操作在下面的Pandas中表达。

保留某些列#

In [1]: tips[["sex", "total_bill", "tip"]]
Out[1]: 
        sex  total_bill   tip
0    Female       14.99  1.01
1      Male        8.34  1.66
2      Male       19.01  3.50
3      Male       21.68  3.31
4    Female       22.59  3.61
..      ...         ...   ...
239    Male       27.03  5.92
240  Female       25.18  2.00
241    Male       20.67  2.00
242    Male       15.82  1.75
243  Female       16.78  3.00

[244 rows x 3 columns]

删除一列#

In [2]: tips.drop("sex", axis=1)
Out[2]: 
     total_bill   tip smoker   day    time  size
0         14.99  1.01     No   Sun  Dinner     2
1          8.34  1.66     No   Sun  Dinner     3
2         19.01  3.50     No   Sun  Dinner     3
3         21.68  3.31     No   Sun  Dinner     2
4         22.59  3.61     No   Sun  Dinner     4
..          ...   ...    ...   ...     ...   ...
239       27.03  5.92     No   Sat  Dinner     3
240       25.18  2.00    Yes   Sat  Dinner     2
241       20.67  2.00    Yes   Sat  Dinner     2
242       15.82  1.75     No   Sat  Dinner     2
243       16.78  3.00     No  Thur  Dinner     2

[244 rows x 6 columns]

重命名列#

In [1]: tips.rename(columns={"total_bill": "total_bill_2"})
Out[1]: 
     total_bill_2   tip     sex smoker   day    time  size
0           14.99  1.01  Female     No   Sun  Dinner     2
1            8.34  1.66    Male     No   Sun  Dinner     3
2           19.01  3.50    Male     No   Sun  Dinner     3
3           21.68  3.31    Male     No   Sun  Dinner     2
4           22.59  3.61  Female     No   Sun  Dinner     4
..            ...   ...     ...    ...   ...     ...   ...
239         27.03  5.92    Male     No   Sat  Dinner     3
240         25.18  2.00  Female    Yes   Sat  Dinner     2
241         20.67  2.00    Male    Yes   Sat  Dinner     2
242         15.82  1.75    Male     No   Sat  Dinner     2
243         16.78  3.00  Female     No  Thur  Dinner     2

[244 rows x 7 columns]

按值排序#

SAS中的排序通过以下方式完成 PROC SORT

proc sort data=tips;
    by sex total_bill;
run;

Pandas有一种 DataFrame.sort_values() 方法,该方法接受要排序的列的列表。

In [1]: tips = tips.sort_values(["sex", "total_bill"])

In [2]: tips
Out[2]: 
     total_bill    tip     sex smoker   day    time  size
67         1.07   1.00  Female    Yes   Sat  Dinner     1
92         3.75   1.00  Female    Yes   Fri  Dinner     2
111        5.25   1.00  Female     No   Sat  Dinner     1
145        6.35   1.50  Female     No  Thur   Lunch     2
135        6.51   1.25  Female     No  Thur   Lunch     2
..          ...    ...     ...    ...   ...     ...   ...
182       43.35   3.50    Male    Yes   Sun  Dinner     3
156       46.17   5.00    Male     No   Sun  Dinner     6
59        46.27   6.73    Male     No   Sat  Dinner     4
212       46.33   9.00    Male     No   Sat  Dinner     4
170       48.81  10.00    Male    Yes   Sat  Dinner     3

[244 rows x 7 columns]

字符串处理#

查找字符串的长度#

参数确定字符串的长度。 LENGTHNLENGTHC 功能。 LENGTHN 不包括尾随空格和 LENGTHC 包括尾随空格。

data _null_;
set tips;
put(LENGTHN(time));
put(LENGTHC(time));
run;

您可以使用以下命令来计算字符串的长度 Series.str.len() 。在Python3中,所有字符串都是Unicode字符串。 len 包括尾随空格。使用 lenrstrip 以排除尾随空格。

In [1]: tips["time"].str.len()
Out[1]: 
67     6
92     6
111    6
145    5
135    5
      ..
182    6
156    6
59     6
212    6
170    6
Name: time, Length: 244, dtype: int64

In [2]: tips["time"].str.rstrip().str.len()
Out[2]: 
67     6
92     6
111    6
145    5
135    5
      ..
182    6
156    6
59     6
212    6
170    6
Name: time, Length: 244, dtype: int64

查找子串的位置#

参数确定字符在字符串中的位置。 FINDW 功能。 FINDW 获取由第一个参数定义的字符串,并搜索作为第二个参数提供的子字符串的第一个位置。

data _null_;
set tips;
put(FINDW(sex,'ale'));
run;

属性可以找到字符在字符串列中的位置 Series.str.find() 方法。 find 搜索子字符串的第一个位置。如果找到子字符串,则该方法返回其位置。如果未找到,则返回 -1 。请记住,Python索引是从零开始的。

In [1]: tips["sex"].str.find("ale")
Out[1]: 
67     3
92     3
111    3
145    3
135    3
      ..
182    1
156    1
59     1
212    1
170    1
Name: sex, Length: 244, dtype: int64

按位置提取子串#

SAS根据子字符串与 SUBSTR 功能。

data _null_;
set tips;
put(substr(sex,1,1));
run;

对于Pandas,你可以使用 [] 按位置从字符串中提取子字符串的表示法。请记住,Python索引是从零开始的。

In [1]: tips["sex"].str[0:1]
Out[1]: 
67     F
92     F
111    F
145    F
135    F
      ..
182    M
156    M
59     M
212    M
170    M
Name: sex, Length: 244, dtype: object

提取第n个单词#

美国航空公司 SCAN 函数返回字符串中的第n个单词。第一个参数是要解析的字符串,第二个参数指定要提取哪个单词。

data firstlast;
input String $60.;
First_Name = scan(string, 1);
Last_Name = scan(string, -1);
datalines2;
John Smith;
Jane Cook;
;;;
run;

在Pandas中提取单词的最简单方法是用空格分割字符串,然后按索引引用单词。请注意,如果您需要的话,还有更强大的方法。

In [1]: firstlast = pd.DataFrame({"String": ["John Smith", "Jane Cook"]})

In [2]: firstlast["First_Name"] = firstlast["String"].str.split(" ", expand=True)[0]

In [3]: firstlast["Last_Name"] = firstlast["String"].str.rsplit(" ", expand=True)[1]

In [4]: firstlast
Out[4]: 
       String First_Name Last_Name
0  John Smith       John     Smith
1   Jane Cook       Jane      Cook

更改大小写#

美国航空公司 UPCASE LOWCASEPROPCASE 函数会更改参数的大小写。

data firstlast;
input String $60.;
string_up = UPCASE(string);
string_low = LOWCASE(string);
string_prop = PROPCASE(string);
datalines2;
John Smith;
Jane Cook;
;;;
run;

等同的Pandas方法是 Series.str.upper()Series.str.lower() ,以及 Series.str.title()

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]: firstlast
Out[5]: 
       string       upper       lower       title
0  John Smith  JOHN SMITH  john smith  John Smith
1   Jane Cook   JANE COOK   jane cook   Jane Cook

合并中#

合并示例中将使用以下表格:

In [1]: df1 = pd.DataFrame({"key": ["A", "B", "C", "D"], "value": np.random.randn(4)})

In [2]: df1
Out[2]: 
  key     value
0   A  0.469112
1   B -0.282863
2   C -1.509059
3   D -1.135632

In [3]: df2 = pd.DataFrame({"key": ["B", "D", "D", "E"], "value": np.random.randn(4)})

In [4]: df2
Out[4]: 
  key     value
0   B  1.212112
1   D -0.173215
2   D  0.119209
3   E -1.044236

在SAS中,数据必须在合并之前显式排序。不同类型的联接是使用 in= 用于跟踪在一个输入帧或两个输入帧中是否找到匹配的虚拟变量。

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的DataFrame有一个 merge() 方法,该方法提供类似的功能。数据不必提前排序,不同的连接类型通过 how 关键字。

In [1]: inner_join = df1.merge(df2, on=["key"], how="inner")

In [2]: inner_join
Out[2]: 
  key   value_x   value_y
0   B -0.282863  1.212112
1   D -1.135632 -0.173215
2   D -1.135632  0.119209

In [3]: left_join = df1.merge(df2, on=["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和SA都有缺失数据的表示法。

Pandas用特殊的浮点值表示丢失的数据 NaN (不是一个数字)。许多语义都是相同的;例如,丢失的数据通过数字操作传播,并且默认情况下,聚合会忽略这些数据。

In [1]: outer_join
Out[1]: 
  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

In [2]: outer_join["value_x"] + outer_join["value_y"]
Out[2]: 
0         NaN
1    0.929249
2         NaN
3   -1.308847
4   -1.016424
5         NaN
dtype: float64

In [3]: outer_join["value_x"].sum()
Out[3]: -3.5940742896293765

一个不同之处在于,不能将丢失的数据与其前哨数值进行比较。例如,在SAS中,您可以这样做来过滤遗漏的值。

data outer_join_nulls;
    set outer_join;
    if value_x = .;
run;

data outer_join_no_nulls;
    set outer_join;
    if value_x ^= .;
run;

在Pandas身上, Series.isna()Series.notna() 可用于筛选行。

In [1]: outer_join[outer_join["value_x"].isna()]
Out[1]: 
  key  value_x   value_y
5   E      NaN -1.044236

In [2]: outer_join[outer_join["value_x"].notna()]
Out[2]: 
  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

Pandas提供了 a variety of methods to work with missing data 。以下是一些例子:

删除缺少值的行#

In [3]: outer_join.dropna()
Out[3]: 
  key   value_x   value_y
1   B -0.282863  1.212112
3   D -1.135632 -0.173215
4   D -1.135632  0.119209

从前一行向前填充#

In [4]: outer_join.fillna(method="ffill")
Out[4]: 
  key   value_x   value_y
0   A  0.469112       NaN
1   B -0.282863  1.212112
2   C -1.509059  1.212112
3   D -1.135632 -0.173215
4   D -1.135632  0.119209
5   E -1.135632 -1.044236

用指定值替换缺少的值#

使用平均值:

In [1]: outer_join["value_x"].fillna(outer_join["value_x"].mean())
Out[1]: 
0    0.469112
1   -0.282863
2   -1.509059
3   -1.135632
4   -1.135632
5   -0.718815
Name: value_x, dtype: float64

GroupBy#

聚合#

SAS的 PROC SUMMARY 可用于按一个或多个键变量分组并计算数字列上的聚合。

proc summary data=tips nway;
    class sex smoker;
    var total_bill tip;
    output out=tips_summed sum=;
run;

Pandas提供了一种灵活的 groupby 允许类似聚合的机制。请参阅 groupby documentation 获取更多详细信息和示例。

In [1]: tips_summed = tips.groupby(["sex", "smoker"])[["total_bill", "tip"]].sum()

In [2]: tips_summed
Out[2]: 
               total_bill     tip
sex    smoker                    
Female No          869.68  149.77
       Yes         527.27   96.74
Male   No         1725.75  302.00
       Yes        1217.07  183.07

转型#

在SA中,如果组聚合需要与原始帧一起使用,则必须将其重新合并在一起。例如,减去吸烟者组每个观察值的平均值。

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提供了一种 转型 一种机制,允许在一个操作中简洁地表达这些类型的操作。

In [1]: gb = tips.groupby("smoker")["total_bill"]

In [2]: tips["adj_total_bill"] = tips["total_bill"] - gb.transform("mean")

In [3]: tips
Out[3]: 
     total_bill    tip     sex smoker   day    time  size  adj_total_bill
67         1.07   1.00  Female    Yes   Sat  Dinner     1      -17.686344
92         3.75   1.00  Female    Yes   Fri  Dinner     2      -15.006344
111        5.25   1.00  Female     No   Sat  Dinner     1      -11.938278
145        6.35   1.50  Female     No  Thur   Lunch     2      -10.838278
135        6.51   1.25  Female     No  Thur   Lunch     2      -10.678278
..          ...    ...     ...    ...   ...     ...   ...             ...
182       43.35   3.50    Male    Yes   Sun  Dinner     3       24.593656
156       46.17   5.00    Male     No   Sun  Dinner     6       28.981722
59        46.27   6.73    Male     No   Sat  Dinner     4       29.081722
212       46.33   9.00    Male     No   Sat  Dinner     4       29.141722
170       48.81  10.00    Male    Yes   Sat  Dinner     3       30.053656

[244 rows x 8 columns]

按分组处理#

除了聚集,大Pandas groupby 可用于通过组处理从SAS复制大多数其他对象。例如,这一点 DATA 步骤按性别/吸烟者组读取数据,并过滤到每个组的第一个条目。

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;

在Pandas中,这将被写成:

In [4]: tips.groupby(["sex", "smoker"]).first()
Out[4]: 
               total_bill   tip   day    time  size  adj_total_bill
sex    smoker                                                      
Female No            5.25  1.00   Sat  Dinner     1      -11.938278
       Yes           1.07  1.00   Sat  Dinner     1      -17.686344
Male   No            5.51  2.00  Thur   Lunch     2      -11.678278
       Yes           5.25  5.15   Sun  Dinner     2      -13.506344

其他考虑事项#

磁盘VS内存#

Pandas只在内存中运行,SAS数据集存在于磁盘上。这意味着可以加载到Pandas中的数据大小受到计算机内存的限制,但对这些数据的操作可能会更快。

如果需要核心外处理,一种可能性是 dask.dataframe 库(目前正在开发中),它为磁盘上的PANDA功能提供了一个子集 DataFrame

数据互操作#

Pandas提供了一种 read_sas() 可以读取以XPORT或SAS7BDAT二进制格式保存的SAS数据的方法。

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")
df = pd.read_sas("binary-file.sas7bdat")

您也可以直接指定文件格式。默认情况下,Pandas会尝试根据其扩展名推断文件格式。

df = pd.read_sas("transport-file.xpt", format="xport")
df = pd.read_sas("binary-file.sas7bdat", format="sas7bdat")

XPORT是一种相对有限的格式,它的解析没有像其他一些Pandas阅读器那样优化。在SAS和PANDA之间互操作数据的另一种方法是序列化到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