- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这个问题类似于this one ,但有一个关键的区别 - 当数据帧分组到 bin 中时,链接问题的解决方案并不能解决问题。
以下代码对 2 个变量的箱的相对分布进行箱线图会产生错误:
import pandas as pd
import seaborn as sns
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])
df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()
df1.fillna(0, inplace=True)
sns.boxplot(x='regiment', y='preTestScore', data=df1)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-241-fc8036eb7d0b> in <module>()
----> 1 sns.boxplot(x='regiment', y='preTestScore', data=df1)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in boxplot(x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth, whis, notch, ax, **kwargs)
2209 plotter = _BoxPlotter(x, y, hue, data, order, hue_order,
2210 orient, color, palette, saturation,
-> 2211 width, dodge, fliersize, linewidth)
2212
2213 if ax is None:
~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in __init__(self, x, y, hue, data, order, hue_order, orient, color, palette, saturation, width, dodge, fliersize, linewidth)
439 width, dodge, fliersize, linewidth):
440
--> 441 self.establish_variables(x, y, hue, data, orient, order, hue_order)
442 self.establish_colors(color, palette, saturation)
443
~\AppData\Local\Continuum\anaconda3\lib\site-packages\seaborn\categorical.py in establish_variables(self, x, y, hue, data, orient, order, hue_order, units)
149 if isinstance(input, string_types):
150 err = "Could not interpret input '{}'".format(input)
--> 151 raise ValueError(err)
152
153 # Figure out the plotting orientation
ValueError: Could not interpret input 'regiment'
如果我删除 x
和 y
参数,它会生成一个箱线图,但它不是我想要的:
我该如何解决这个问题?我尝试了以下方法:
df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()
df1.fillna(0, inplace=True)
df1 = df1.reset_index()
df1
它现在看起来像一个数据框,所以我想到提取该数据框的列名称并按顺序绘制每个列:
cols = df1.columns[1:len(df1.columns)]
for i in range(len(cols)):
sns.boxplot(x='regiment', y=cols[i], data=df1)
这看起来不对。事实上,这不是一个普通的数据框;如果我们打印出它的列,它不会将 regiment
显示为列,这就是为什么 boxplot 给出错误 ValueError: Could notterpret input 'regiment'
:
df1.columns
>>> Index(['regiment', 2, 3, 4, 24, 31], dtype='object', name='preTestScore')
所以,如果我能以某种方式使 regiment
成为数据框的一列,我想我应该能够绘制 preTestScore
与 regiment< 的箱线图
。我错了吗?
编辑:我想要的是这样的:
df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()
df1.fillna(0, inplace=True)
# This df2 dataframe is the one I'm trying to construct using groupby
data = {'regiment':['Dragoons', 'Nighthawks', 'Scouts'], 'preTestScore 2':[0.0, 1.0, 2.0], 'preTestScore 3':[1.0, 0.0, 2.0],
'preTestScore 4':[1.0, 1.0, 0.0], 'preTestScore 24':[1.0, 1.0, 0.0], 'preTestScore 31':[1.0, 1.0, 0.0]}
cols = ['regiment', 'preTestScore 2', 'preTestScore 3', 'preTestScore 4', 'preTestScore 24', 'preTestScore 31']
df2 = pd.DataFrame(data, columns=cols)
df2
fig = plt.figure(figsize=(20,3))
count = 1
for col in cols[1:]:
plt.subplot(1, len(cols)-1, count)
sns.boxplot(x='regiment', y=col, data=df2)
count+=1
最佳答案
如果您对数据帧df1
执行reset_index()
,您应该获得您想要的数据帧。
问题是您有一个所需的列(regiment
)作为索引,因此您需要重置它并将其设为另一列。
编辑:为结果数据框中正确的列名称添加了add_prefix
示例代码:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
raw_data = {'regiment': ['Nighthawks', 'Nighthawks', 'Nighthawks', 'Nighthawks', 'Dragoons', 'Dragoons', 'Dragoons', 'Dragoons', 'Scouts', 'Scouts', 'Scouts', 'Scouts'],
'company': ['1st', '1st', '2nd', '2nd', '1st', '1st', '2nd', '2nd','1st', '1st', '2nd', '2nd'],
'name': ['Miller', 'Jacobson', 'Ali', 'Milner', 'Cooze', 'Jacon', 'Ryaner', 'Sone', 'Sloan', 'Piger', 'Riani', 'Ali'],
'preTestScore': [4, 24, 31, 2, 3, 4, 24, 31, 2, 3, 2, 3],
'postTestScore': [25, 94, 57, 62, 70, 25, 94, 57, 62, 70, 62, 70]}
df = pd.DataFrame(raw_data, columns = ['regiment', 'company', 'name', 'preTestScore', 'postTestScore'])
df1 = df.groupby(['regiment'])['preTestScore'].value_counts().unstack()
df1.fillna(0, inplace=True)
df1 = df1.add_prefix('preTestScore ') # <- add_prefix for proper column names
df2 = df1.reset_index() # <- Here is reset_index()
cols = df2.columns
fig = plt.figure(figsize=(20,3))
count = 1
for col in cols[1:]:
plt.subplot(1, len(cols)-1, count)
sns.boxplot(x='regiment', y=col, data=df2)
count+=1
关于python - 分箱后无法访问数据帧的 groupby 对象的各个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51851956/
给定输入: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 将数字按奇数或偶数分组,然后按小于或大于 5 分组。 预期输出: [[1, 3, 5], [2, 4], [6, 8, 10
编辑: @coldspeed、@wen-ben、@ALollz 指出了我在字符串 np.nan 中犯的新手错误。答案很好,所以我不删除这个问题来保留那些答案。 原文: 我读过这个问题/答案 What'
我试图概括我提出的问题 here . mlb 数据框看起来像 Player Position Salary Year 0 Mike Wit
我认为我不需要共享整个数据框,但基本上,这是有问题的代码行(当然,已经导入了 pandas) divstack = df[df['Competitor']=='Emma Slabach'].group
我面临下一个问题:我有组(按 ID),对于所有这些组,我需要应用以下代码:如果组内位置之间的距离在 3 米以内,则需要将它们添加在一起,因此将创建一个新组(代码如何创建我在下面显示的组)。现在,我想要
我有以下数据: ,dateTime,magnitude,occurrence,dateTime_s 1,2017-11-20 08:00:09.052260,12861,1,2017-11-20 08
我按感兴趣的列对 df 进行分组: grouped = df.groupby('columnA') 现在我只想保留至少有 5 名成员的组: grouped.filter(lambda x: len(x
数据是一个时间序列,许多成员 ID 与许多类别相关联: data_df = pd.DataFrame({'Date': ['2018-09-14 00:00:22',
选择 u.UM_TOKEN_NO 、u.UM_FULLNAME、u.SECTOR、u.department_name、t.TS_PROJECT_CODE、sum(t.TS_TOTAL_HRS) 来自
我有这两个表: +---------------+-------------+---------------------+----------+---------+ | items_ordered |
我正在使用 groupby 和 sum 快速汇总两个数据集 一个包含: sequence shares 1 100 2 200 3 50 1 2
这个问题在这里已经有了答案: list around groupby results in empty groups (3 个答案) itertools groupby object not out
我有一组行,我想按标识符的值进行分组 - 存在于每一行中 - 然后对将作为结果的组进行进一步的隔离处理。 我的数据框是这样的: In [50]: df Out[50]: groupkey b
假设您要在全局范围内销售产品,并且希望在某个主要城市的某个地方设立销售办事处。您的决定将完全基于销售数字。 这将是您的(简化的)销售数据: df={ 'Product':'Chair', 'Count
我有一个将数据分组两次的查询: var query = (from a in Context.SetA() from b in Context.SetB().Where(x => x.aId == a
我有一个这种格式的数据框: value identifier 2007-01-01 0.087085 55 2007-01-01 0.703249
这个问题在这里已经有了答案: python groupby behaviour? (3 个答案) 关闭 4 年前。 我有一个这样的列表 [u'201003', u'200403', u'200803
在 Python 中,我可以使用 itertools.groupby 将具有相同键的连续元素分组。 : >>> items = [(1, 2), (1, 5), (1, 3), (2, 9), (3,
无法翻译以下 GroupBy 查询并将引发错误:不支持客户端 GroupBy IEnumerable ids = new List { 1, 2, 3 }; var q = db.Comments.W
考虑一个 Spark DataFrame,其中只有很少的列。目标是对其执行 groupBy 操作,而不将其转换为 Pandas DataFrame。等效的 Pandas groupBy 代码如下所示:
我是一名优秀的程序员,十分优秀!