Advanced Python Pandas

Merging DataFrames

语法如下:
merge(left, right, how='inner', on=None, left_on=None, right_on=None,
left_index=False, right_index=False, sort=True,
suffixes=('_x', '_y'), copy=True, indicator=False)

参数说明:

  1. left 与 right:两个不同的 DataFrame
  2. how:指的是合并(连接)的方式有 inner(内连接), left(左外连接), right(右外连接), outer(全外连接); 默认为 inner
  3. on: 指的是用于连接的列索引名称。必须存在右右两个 DataFrame 对象中,如果没有指定且其他参数也未指定则以两个 DataFrame 的列名交集做为连接键
  4. left_on:左则 DataFrame 中用作连接键的列名;这个参数中左右列名不相同,但代表的含义相同时非常有用。
  5. right_on:右则 DataFrame 中用作 连接键的列名
  6. left_index:使用左则 DataFrame 中的行索引做为连接键
  7. right_index:使用右则 DataFrame 中的行索引做为连接键
  8. sort:默认为 True,将合并的数据进行排序。在大多数情况下设置为 False 可以提高性能
  9. suffixes:字符串值组成的元组,用于指定当左右DataFrame存在相同列名时在列名后面附加的后缀名称,默认为 ('_x','_y')
  10. copy:默认为 True,总是将数据复制到数据结构中;大多数情况下设置为False可以提高性能
  11. indicator:在 0.17.0 中还增加了一个显示合并数据中来源情况;如只来自己于左边(left_only)、两者(both)

Idiomatic Pandas: Making Code Pandorable

用连续的函数加换行增加代码的可读性:
(df.where(df['SUMLEV']==50)
.dropna()
.set_index(['STNAME','CTYNAME'])
.rename(columns={'ESTIMATESBASE2010': 'Estimates Base 2010'}))

注意到,给 column 重命名的代码:df.rename(column={'original_name': 'new_name'})

Group by

  • 遍历 groupby,用for group, frame in df.groupby('NAME’),group 是分组的依据,如果 ’NAME’ 是一个函数,那么 group 就是 return 的值;frame 是每一个 NAME 后面的 DataFrame。要数每一个的个数,就用 len(frame)
  • groupby(level=0), if the axis is a MultiIndex (hierarchical), group by a particular level or levels.
  • df.groupby('Category').apply(lambda df,a,b: sum(df[a] * df[b]), 'Weight (oz.)', 'Quantity'). It uses function on certain column and output after groupby.

Scales

  • Ratio scale: units are equally spaced; mathematical operations of +-*/ is valid. e.g. weight and height.
  • Interval scale: units are equally spaced; it cannot use operations of * and /. e.g. 1-5 in the questionnaire.
  • Ordinal scale: the order of units are important but not evenly spaced. e.g. letter grade A+, A and A-.
  • Nominal scale: category of data, but category has no order. e.g. teams of a sport.
  • df['Grades'].astype('category'), transfer to categorical data. Or, grades = df['Grades'].astype('category', categories=['D', 'D+', 'C-', 'C', 'C+', 'B-', 'B', 'B+', 'A-', 'A', 'A+'], ordered=True), make category in ascending order.
  • s = pd.Series([168, 180, 174, 190, 170, 185, 179, 181, 175, 169, 182, 177, 180, 171]). Use pd.cut to bin this data into 3 bins (we can also label them): pd.cut(s, 3, labels=['Small', 'Medium', 'Large']).

Pivot Tables

语法如下:
pivot_table(df, values=, index=, columns=, aggfunc=np.mean, margins=False)

if margins=True, special All(default is np.mean) columns and rows will be added with partial group aggregates.

Date Functionality

  • Timestamp: pd.Timestamp('9/1/2016 10:05AM')

  • Period: pd.Period('1/2016') or pd.Period('3/5/2016')

  • Datetime index: pd.Series(list('abc'), [pd.Timestamp('2016-09-01'), pd.Timestamp('2016-09-02'), pd.Timestamp('2016-09-03')])

output:
2016-09-01 a
2016-09-02 b
2016-09-03 c
dtype: object

  • Similarly, period index: pd.Series(list('def'), [pd.Period('2016-09'), pd.Period('2016-10'), pd.Period('2016-11')])
  • Converting to datetime: pd.to_datetime(arg, dayfirst=False, yearfirst=False)
  • Timedeltas: pd.Timestamp('9/2/2016 8:10AM') + pd.Timedelta('12D 3H')

Working with Dates in Dataframe

  • Date range: pd.date_range(start=None, end=None, periods=None, freq=’D’, tz=None, normalize=False, name=None, closed=None).

  • freq: (freq aliases in the attachment image)

  • tz: Time zone name for returning localized DatetimeIndex, for example Asia/Hong_Kong.

  • closed: Make the interval closed with respect to the given frequency to the ‘left’, ‘right’, or both sides (None).

  • Example: dates = pd.date_range('10-01-2016', periods=9, freq='2W-SUN')

  • 查看 index 分别是星期几:df.index.weekday_name.

  • 直接进行差分,比如求 return:df.diff().

  • Resample: df.resample(rule, fill_method=None, closed=None, label=None). closed/lable: ‘left’ or ‘right’.

  • Example: 归总求每个月的均值 df.resample('M').mean().

  • Query with date: df['2016-12'] or df['2016-12':].

  • 重新排列 freq: df.asfreq(freq, method=None). Method=‘bfill’/‘ffill’.

Other

  • 把 DataFrame 里的 a 换成 b:df.replace('a', 'b')
  • 替换 DataFrame 里有一定规律的字符串:. 代表任意字符; * 代表 0 个以上重复字符; + 代表 1 个以上重复字符; [] 表示 list 里面出现的都替换掉;具体参见文档字符串说明。
  • Groupby 以后计数或求均值等:gourpby('column_A').agg({'column_B': ['size', 'sum'], 'column_C':['count', 'mean', 'max']})

你可能感兴趣的:(Advanced Python Pandas)