我在The Billionaire Characteristics Database数据集上练习我的ML分类技能。
我正在使用sframe
来加载和操作数据,seaborn
用于可视化。
在数据分析过程中,我想绘制一个按分类变量分组的箱形图,如seaborn
教程中的这个:
在数据集中,有一个networthusbillion
数字变量和selfmade
分类变量,用于说明亿万富翁是self-made
还是({)他有inherited
美元。< / p>
当我尝试使用sns.boxplot(x='selfmade', y='networthusbillion', data=data)
绘制类似的方框图时,会抛出以下错误:
---------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-17-f4bd651c2ae7> in <module>()
----> 1 sns.boxplot(x='selfmade', y='networthusbillion', data=billionaires)
/home/iulian/.virtualenvs/data-science-python2/lib/python2.7/site-packages/seaborn/categorical.pyc in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, fliersize, linewidth, whis, notch, ax, **kwargs)
2127 plotter = _BoxPlotter(x, y, hue, data, order, hue_order,
2128 orient, color, palette, saturation,
-> 2129 width, fliersize, linewidth)
2130
2131 if ax is None:
/home/iulian/.virtualenvs/data-science-python2/lib/python2.7/site-packages/seaborn/categorical.pyc in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, fliersize, linewidth)
420 width, fliersize, linewidth):
421
--> 422 self.establish_variables(x, y, hue, data, orient, order, hue_order)
423 self.establish_colors(color, palette, saturation)
424
/home/iulian/.virtualenvs/data-science-python2/lib/python2.7/site-packages/seaborn/categorical.pyc in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
136 # See if we need to get variables from `data`
137 if data is not None:
--> 138 x = data.get(x, x)
139 y = data.get(y, y)
140 hue = data.get(hue, hue)
AttributeError: 'SFrame' object has no attribute 'get'
我尝试了以下表格来绘制方块图 - 它们都没有达到结果:
sns.boxplot(x=billionaires['selfmade'], y=billionaires['networthusbillion'])
sns.boxplot(x='selfmade', y='networthusbillion', data=billionaires['selfmade', 'networthusbillion'])
但是,我可以使用sframe
绘制一个方框图,但不按selfmade
分组:
sns.boxplot(x=billionaires['networthusbillion'])
所以,我的问题是:有没有办法使用sframe
绘制按分类变量分组的箱形图?也许我做错了什么?
顺便说一句,我设法使用pandas.DataFrame
使用相同的语法(sns.boxplot(x='selfmade', y='networthusbillion', data=data)
)绘制它,因此可能使用sframe
和seaborn
进行分组已实施。
答案 0 :(得分:0)
问题在于sns.boxplot
期望数据具有像{Pandas&#39;}这样的get
方法。数据帧。在Pandas中,get
方法返回单个列,因此它与括号索引相同,即your_df['your_column_name']
。
解决此问题的最简单方法是在sframe上调用to_dataframe
方法将其转换为数据框。
sns.boxplot(x='selfmade', y='networthusbillion', data=data.to_dataframe())
或者,您可以通过编写类包装器或使用monkey-patching get
到SFrame类来解决问题。
import numpy as np
import sframe
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# For demostration purposes
def to_sframe(df):
import sframe
d = {}
for key in df.keys():
d[key] = list(df[key])
return sframe.SFrame(d)
pd.DataFrame.to_sframe = to_sframe
tips = sns.load_dataset('tips')
# Monkey patch sframe's get and _CategoricalPlotter's _group_longform
def get(self, *args):
key = args[0]
return self.__getitem__(key) if key else None
sframe.SFrame.get = get
def _group_longform(self, vals, grouper, order):
"""Group a long-form variable by another with correct order."""
#import pdb;pdb.set_trace()
if type(vals) == sframe.SArray:
_sf = sframe.SFrame({'vals':vals, 'grouper':grouper})
grouped_vals = _sf.groupby('grouper', sframe.aggregate.CONCAT('vals'))
out_data = []
for g in order:
try:
g_vals = np.asarray(grouped_vals.filter_by(g, 'grouper')["List of vals"][0])
except KeyError:
g_vals = np.array([])
out_data.append(g_vals)
label = ""
return out_data, label
## Code copied from original _group_longform
# Ensure that the groupby will work
if not isinstance(vals, pd.Series):
vals = pd.Series(vals)
# Group the val data
grouped_vals = vals.groupby(grouper)
out_data = []
for g in order:
try:
g_vals = np.asarray(grouped_vals.get_group(g))
except KeyError:
g_vals = np.array([])
out_data.append(g_vals)
# Get the vals axis label
label = vals.name
return out_data, label
sns.categorical._CategoricalPlotter._group_longform = _group_longform
# Plots should be equivalent
#1.
plt.figure()
sns.boxplot(x="day", y="total_bill", data=tips)
#2.
plt.figure()
sns.boxplot(x="day", y="total_bill", data=tips.to_sframe(),
order=["Thur", "Fri", "Sat", "Sun"])
plt.xlabel("day")
plt.ylabel("total_bill")
plt.show()
答案 1 :(得分:0)
使用sframe
与seaborn
进行分组尚未实施。
在深入了解seaborn的源代码后,我发现它专门设计用于pandas.DataFrame
。在他们的回答中采用绝对无保证的建议,我得到以下错误:
TypeError: __getitem__() takes exactly 2 arguments (3 given)
看一下args
电话中的get
,有以下数据:
('gender', 'gender')
这是因为BoxPlot
的源代码中的代码:
# See if we need to get variables from `data`
if data is not None:
x = data.get(x, x)
y = data.get(y, y)
hue = data.get(hue, hue)
units = data.get(units, units)
它尝试获取值并使用相同的值作为后备,以防它不存在。这会导致__getitem__()
出错,因为它会被(self, 'gender', 'gender')
个参数调用。
我尝试重写get()
函数,如下所示:
def get(self, *args):
return self.__getitem__(args[0]) if args[0] else None # The `None` is here because the `units` in the source code is `None` for boxplots.
在这里,我收到了错误,结束了我的尝试:
TypeError: 'SArray' object is not callable
查看源代码,它会检查y
数据是否为pd.Series
,如果不是,则将y
值转换为1:
if not isinstance(vals, pd.Series):
vals = pd.Series(vals)
# Group the val data
grouped_vals = vals.groupby(grouper)
当执行vals.groupby(grouper)
(石斑鱼仍然是SArray
实例)时,它会进入pandas核心工作区,其中调用SArray
并抛出错误。故事结束。