有没有办法编写DataFrame.agg方法中使用的聚合函数,可以访问聚合的多个数据列?典型的用例是加权平均加权标准偏差函数.
我希望能够写出类似的东西
def wAvg(c, w):
return ((c * w).sum() / w.sum())
df = DataFrame(....) # df has columns c and w, i want weighted average
# of c using w as weight.
df.aggregate ({"c": wAvg}) # and somehow tell it to use w column as weights ...
Run Code Online (Sandbox Code Playgroud) 我有一个数据帧,
Out[78]:
contract month year buys adjusted_lots price
0 W Z 5 Sell -5 554.85
1 C Z 5 Sell -3 424.50
2 C Z 5 Sell -2 424.00
3 C Z 5 Sell -2 423.75
4 C Z 5 Sell -3 423.50
5 C Z 5 Sell -2 425.50
6 C Z 5 Sell -3 425.25
7 C Z 5 Sell -2 426.00
8 C Z 5 Sell -2 426.75
9 CC U 5 Buy 5 3328.00
10 SB …Run Code Online (Sandbox Code Playgroud) 我有一个如下所示的数据框:
Out[14]:
impwealth indweight
16 180000 34.200
21 384000 37.800
26 342000 39.715
30 1154000 44.375
31 421300 44.375
32 1210000 45.295
33 1062500 45.295
34 1878000 46.653
35 876000 46.653
36 925000 53.476
Run Code Online (Sandbox Code Playgroud)
我想impwealth用频率权重计算列的加权中位数indweight.我的伪代码看起来像这样:
# Sort `impwealth` in ascending order
df.sort('impwealth', 'inplace'=True)
# Find the 50th percentile weight, P
P = df['indweight'].sum() * (.5)
# Search for the first occurrence of `impweight` that is greater than P
i = df.loc[df['indweight'] > P, 'indweight'].last_valid_index()
# The …Run Code Online (Sandbox Code Playgroud) 我对python和pandas(使用SAS作为我的主力分析平台)相当新,所以如果已经被问到/已经回答过,我会事先道歉.(我搜索了文档以及这个网站搜索答案,但还没找到.)
我有一个包含受访者级别调查数据的数据框(称为resp).我想对其中一个字段(称为anninc [年收入的简称])执行一些基本的描述性统计.
resp["anninc"].describe()
Run Code Online (Sandbox Code Playgroud)
这给了我基本的统计数据:
count 76310.000000
mean 43455.874862
std 33154.848314
min 0.000000
25% 20140.000000
50% 34980.000000
75% 56710.000000
max 152884.330000
dtype: float64
Run Code Online (Sandbox Code Playgroud)
但是有一个问题.鉴于样本是如何构建的,需要对响应数据进行权重调整,以便在执行分析时不会将每个数据视为"相等".我在数据框中有另一列(称为tufnwgrp),表示在分析期间应应用于每条记录的权重.
在我之前的SAS生活中,大多数proc都有选项来处理具有这样权重的数据.例如,标准proc单变量给出相同的结果看起来像这样:
proc univariate data=resp;
var anninc;
output out=resp_univars mean=mean median=50pct q1=25pct q3=75pct min=min max=max n=count;
run;
Run Code Online (Sandbox Code Playgroud)
使用加权数据的相同分析看起来像这样:
proc univariate data=resp;
var anninc;
weight tufnwgrp;
output out=resp_univars mean=mean median=50pct q1=25pct q3=75pct min=min max=max n=count
run;
Run Code Online (Sandbox Code Playgroud)
对于像describe()等方法,pandas中是否有类似的加权选项?