如何从具有权重的数据创建箱线图?

时间:2019-09-22 21:39:23

标签: python pandas dataframe data-visualization

我有以下数据:名字出现的次数NameCount),每个名字的Score。我想创建一个Score的方须图,并用其Score加权每个名称的Count

结果应该与原始数据(非频率)形式的数据相同。但是,我实际上并不希望将数据转换为这种格式,因为它会很快使数据膨胀。

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

data = {
    "Name":['Sara', 'John', 'Mark', 'Peter', 'Kate'],
    "Count":[20, 10, 5, 2, 5], 
    "Score": [2, 4, 7, 8, 7]
}
df = pd.DataFrame(data)
print(df)
   Count   Name  Score
0     20   Sara      2
1     10   John      4
2      5   Mark      7
3      2  Peter      8
4      5   Kate      7

我不确定如何在Python中解决此问题。任何帮助表示赞赏!

2 个答案:

答案 0 :(得分:0)

有两种方法可以解决这个问题。您可能会期望第一个,但是对于计算confidence intervals of the median来说不是一个很好的解决方案,它具有使用示例数据的后续代码,引用了matplotlib/cbook/__init__.py。因此,相比其他任何自定义代码,Second都经过了良好的测试,因此比其他任何工具都好得多。

def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None,
                  autorange=False):
    def _bootstrap_median(data, N=5000):
        # determine 95% confidence intervals of the median
        M = len(data)
        percentiles = [2.5, 97.5]

        bs_index = np.random.randint(M, size=(N, M))
        bsData = data[bs_index]
        estimate = np.median(bsData, axis=1, overwrite_input=True)

第一

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = {
    "Name": ['Sara', 'John', 'Mark', 'Peter', 'Kate'],
    "Count": [20, 10, 5, 2, 5],
    "Score": [2, 4, 7, 8, 7]
}

df = pd.DataFrame(data)
print(df)


def boxplot(values, freqs):
    values = np.array(values)
    freqs = np.array(freqs)
    arg_sorted = np.argsort(values)
    values = values[arg_sorted]
    freqs = freqs[arg_sorted]
    count = freqs.sum()
    fx = values * freqs
    mean = fx.sum() / count
    variance = ((freqs * values ** 2).sum() / count) - mean ** 2
    variance = count / (count - 1) * variance  # dof correction for sample variance
    std = np.sqrt(variance)
    minimum = np.min(values)
    maximum = np.max(values)
    cumcount = np.cumsum(freqs)

    print([std, variance])
    Q1 = values[np.searchsorted(cumcount, 0.25 * count)]
    Q2 = values[np.searchsorted(cumcount, 0.50 * count)]
    Q3 = values[np.searchsorted(cumcount, 0.75 * count)]

    '''
    interquartile range (IQR), also called the midspread or middle 50%, or technically
    H-spread, is a measure of statistical dispersion, being equal to the difference
    between 75th and 25th percentiles, or between upper and lower quartiles,[1][2]
    IQR = Q3 −  Q1. In other words, the IQR is the first quartile subtracted from
    the third quartile; these quartiles can be clearly seen on a box plot on the data.
    It is a trimmed estimator, defined as the 25% trimmed range, and is a commonly used
    robust measure of scale.
    '''

    IQR = Q3 - Q1

    '''
    The whiskers add 1.5 times the IQR to the 75 percentile (aka Q3) and subtract
    1.5 times the IQR from the 25 percentile (aka Q1).  The whiskers should include
    99.3% of the data if from a normal distribution.  So the 6 foot tall man from
    the example would be inside the whisker but my 6 foot 2 inch girlfriend would
    be at the top whisker or pass it.
    '''
    whishi = Q3 + 1.5 * IQR
    whislo = Q1 - 1.5 * IQR

    stats = [{
        'label': 'Scores',  # tick label for the boxplot
        'mean': mean,  # arithmetic mean value
        'iqr': Q3 - Q1,  # 5.0,
#         'cilo': 2.0,  # lower notch around the median
#         'cihi': 4.0,  # upper notch around the median
        'whishi': maximum,  # end of the upper whisker
        'whislo': minimum,  # end of the lower whisker
        'fliers': [],  # '\array([], dtype=int64)',  # outliers
        'q1': Q1,  # first quartile (25th percentile)
        'med': Q2,  # 50th percentile
        'q3': Q3  # third quartile (75th percentile)
    }]

    fs = 10  # fontsize
    _, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
    axes.bxp(stats)
    axes.set_title('Default', fontsize=fs)
    plt.show()


boxplot(df['Score'], df['Count'])

第二:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt


data = {
    "Name": ['Sara', 'John', 'Mark', 'Peter', 'Kate'],
    "Count": [20, 10, 5, 2, 5],
    "Score": [2, 4, 7, 8, 7]
}

df = pd.DataFrame(data)
print(df)

labels = ['Scores']

data = df['Score'].repeat(df['Count']).tolist()

# compute the boxplot stats
stats = cbook.boxplot_stats(data, labels=labels, bootstrap=10000)

print(['stats :', stats])

fs = 10  # fontsize

fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharey=True)
axes.bxp(stats)
axes.set_title('Boxplot', fontsize=fs)

plt.show()

参考文献:

答案 1 :(得分:0)

这个问题很晚,但是如果遇到的任何人都有用的话-

当权重为整数时,可以使用reindex扩展计数,然后直接使用boxplot调用。我已经能够在没有存储挑战的情况下将具有数千个数据帧的数据帧变成数十万个数据帧,尤其是如果将实际重新索引的数据帧包装到第二个未在内存中分配功能的函数中。

import pandas as pd
import seaborn as sns

data = {
    "Name": ['Sara', 'John', 'Mark', 'Peter', 'Kate'],
    "Count": [20, 10, 5, 2, 5],
    "Score": [2, 4, 7, 8, 7]
}
df = pd.DataFrame(data)

def reindex_df(df, weight_col):
    """expand the dataframe to prepare for resampling
    result is 1 row per count per sample"""
    df = df.reindex(df.index.repeat(df[weight_col]))
    df.reset_index(drop=True, inplace=True)
    return(df)

df = reindex_df(df, weight_col = 'Count')

sns.boxplot(x='Name', y='Score', data=df)

或者如果您担心内存问题

def weighted_boxplot(df, weight_col):
    sns.boxplot(x='Name', 
                y='Score', 
                data=reindex_df(df, weight_col = weight_col))
    
weighted_boxplot(df, 'Count')