the*_*tie 3 python data-visualization dataframe pandas
我有以下数据:aName名称出现的次数 ( Count),以及Score每个名称的 a 。我想创建 的箱须图,并按Score每个名称的 进行加权。ScoreCount
结果应该与我拥有原始(非频率)形式的数据相同。但我实际上不想将数据转换为这种形式,因为它的大小会很快膨胀。
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)
Run Code Online (Sandbox Code Playgroud)
Count Name Score
0 20 Sara 2
1 10 John 4
2 5 Mark 7
3 2 Peter 8
4 5 Kate 7
Run Code Online (Sandbox Code Playgroud)
我不知道如何在 Python 中解决这个问题。任何帮助表示赞赏!
这个问题迟到了,但如果它对遇到它的人有用的话——
当您的权重是整数时,您可以使用重新索引来按计数扩展,然后直接使用箱线图调用。我已经能够在几千个数据帧上做到这一点,变成几十万个,而不会遇到内存挑战,特别是如果实际重新索引的数据帧被包装到不将其分配到内存中的第二个函数中。
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)
Run Code Online (Sandbox Code Playgroud)
或者如果您担心记忆力
def weighted_boxplot(df, weight_col):
sns.boxplot(x='Name',
y='Score',
data=reindex_df(df, weight_col = weight_col))
weighted_boxplot(df, 'Count')
Run Code Online (Sandbox Code Playgroud)