python - 数据帧 : how do I find value in one column for a quantile in a second column

标签 python pandas quantile

我有一个如下所示的 DataFrame,其中包含日期、偏移量和计数。

例如,这是数据帧的开始

df = pd.DataFrame(np.array([['2018-01-01', 0, 1], ['2018-01-01', 26, 2], ['2018-01-01', 178, 8], ['2018-01-01', 187, 10], ['2018-01-01', 197, 13], ['2018-01-01', 208, 15], ['2018-01-01', 219, 16], ['2018-01-01', 224, 19],['2018-01-01', 232, 21], ['2018-01-01', 233, 25], ['2018-01-01', 236, 32],['2018-01-02', 0, 1], ['2018-01-02', 11, 4], ['2018-01-02', 12, 7], ['2018-01-02', 20, 12], ['2018-01-02', 35, 24], ]), columns=['obs_date', 'offset', 'count'])

    obs_date    offset  count
0   2018-01-01  0       1
1   2018-01-01  26      2
2   2018-01-01  178     8
3   2018-01-01  187     10
4   2018-01-01  197     13
5   2018-01-01  208     15
6   2018-01-01  219     16
7   2018-01-01  224     19
8   2018-01-01  232     21
9   2018-01-01  233     25
10  2018-01-01  236     32
11  2018-01-02  0       1
12  2018-01-02  11      4
13  2018-01-02  12      7
14  2018-01-02  20      12
15  2018-01-02  35      24

等等

我想获取每个日期的(累积)['count'] 分位数 [0.25, 0.5, 0.75],并找到具有该分位数适用的 ['offset'] 的行。 每个日期的总计数会不同,并且偏移量不规则 因此,对于 2018-01-01,日期和偏移量对应的计数为 8、16 和 24 (0.25、0.5、0.75 * 32)

类似的东西

0   2018-01-01  178     0.25
1   2018-01-01  219     0.5
2   2018-01-01  232.75  0.75
3   2018-01-02  43      0.25
etc     

最佳答案

这对我有用:

df['count'] = df['count'].astype(int)
quantiles = [.25, .5, .75]

def get_offset(x):
    s = x['count']
    indices = [(s.sort_values()[::-1] <= s.quantile(q)).idxmax() for q in quantiles]
    return df.iloc[indices, x.columns.get_loc('offset')]

res = df.groupby('obs_date').apply(get_offset).reset_index(level=0)

然后您可以使用分位数concat:

pd.concat([res.reset_index(drop=True), pd.Series(quantiles * df.obs_date.nunique())], axis=1)

    obs_date    offset  0
0   2018-01-01  178     0.25
1   2018-01-01  208     0.50
2   2018-01-01  224     0.75
3   2018-01-02  11      0.25
4   2018-01-02  12      0.50
5   2018-01-02  20      0.75

关于python - 数据帧 : how do I find value in one column for a quantile in a second column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55022631/

相关文章:

python - 使用python Mechanize访问时没有显示网站表,我如何找到它?

python - Pandas - FillNa 具有相似列的另一个非空行

python - Pandas 找到满足条件的日期之间的持续时间?

python - R 中的 qgeom 和 Python 中的 scipy.stats.geom.ppf 有什么区别?

python - enumerate(fileinput.input(file)) 和 enumerate(file) 的区别

python - 使用 flags() 创建一个 QTableWidgetItem

python - 如何动态更新 matplotlib 表格单元格文本

python - 使用 Pandas 保存列中条目的总数

R:如何找到分位数

可靠地检索分位数函数的逆函数