Sha*_*har 25 python pandas seaborn
我有以下代码,通过seaborn创建一个表和一个barplot.
#Building a dataframe grouped by the # of Engagement Types
sales_type = sales.groupby('# of Engagement Types').sum()
#Calculating the % of people who bought the course by # engagement types
sales_type['% Sales per Participants'] = round(100*(sales_type['Sales'] / sales_type['Had an Engagement']), 2)
#Calculating the # of people who didn't have any engagements
sales_type.set_value(index=0, col='Had an Engagement', value=sales[sales['Had an Engagement']==0].count()['Sales'])
#Calculating the % of sales for those who didn't have any engagements
sales_type.set_value(index=0, col='% Sales per Participants',
value=round(100 * (sales_type.ix[0, 'Sales'] /
sales[sales['Had an Engagement']==0].count()['Sales']),2))
#Setting the graph image
fig, (ax1) = plt.subplots(nrows=1, ncols=1, figsize=(12,4))
sns.set_style("whitegrid")
# Ploting the histagram for the % of total prospects
ax1 = sns.barplot(x=sales_type.index,y='% Sales per Participants', data=sales_type ,ax=ax1)
ax1.set(ylabel = '%')
ax1.set_title('% Sales per Participants By # of Engagement Types')
#present the table
sales_type.xs(['Had an Engagement', 'Sales','% Sales per Participants'],axis=1).transpose()
#sales_type
Run Code Online (Sandbox Code Playgroud)
我对其他参数使用相同的代码概念没有问题.但是,对于一个参数,我得到一个错误:"ValueError:Grouper for''not 1-dimensional"for line code:
ax1 = sns.barplot(x=sales_type.index,y='% Sales per Participants', data=sales_type ,ax=ax1)
Run Code Online (Sandbox Code Playgroud)
尽管数据框架没有多个维度,但仍会发生此错误.
这是表格的负责人:
Sales Pre-Ordered / Ordered Book \
# of Engagement Types
0 1.0 0.0
1 20.0 496.0
2 51.0 434.0
3 82.0 248.0
4 71.0 153.0
5 49.0 97.0
6 5.0 24.0
Opted In For / Clicked to Kindle Viewed PLC \
# of Engagement Types
0 0.0 0
1 27034.0 5920
2 6953.0 6022
3 1990.0 1958
4 714.0 746
5 196.0 204
6 24.0 24
# of PLC Engagement Viewed Webinar \
# of Engagement Types
0 0.0 0
1 6434.0 1484
2 7469.0 1521
3 2940.0 1450
4 1381.0 724
5 463.0 198
6 54.0 24
# of Webinars (Live/Replay) \
# of Engagement Types
0 0.0
1 1613.0
2 1730.0
3 1768.0
4 1018.0
5 355.0
6 45.0
OCCC Facebook Group Member Engaged in Cart-Open \
# of Engagement Types
0 0.0 0
1 148.0 160
2 498.0 1206
3 443.0 967
4 356.0 511
5 168.0 177
6 24.0 24
# of Engagement at Cart Open Had an Engagement \
# of Engagement Types
0 0.0 3387
1 189.0 35242
2 1398.0 8317
3 1192.0 2352
4 735.0 801
5 269.0 208
6 40.0 24
Total # of Engagements % Sales per Participants
# of Engagement Types
0 0.0 0.03
1 35914.0 0.06
2 18482.0 0.61
3 8581.0 3.49
4 4357.0 8.86
5 1548.0 23.56
6 211.0 20.83
Run Code Online (Sandbox Code Playgroud)
这是完整的错误:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-211-f0185fe64c1a> in <module>()
12 sns.set_style("whitegrid")
13 # Ploting the histagram for the % of total prospects
---> 14 ax1 = sns.barplot(x=sales_type.index,y='% Sales per Participants', data=sales_type ,ax=ax1)
15 ax1.set(ylabel = '%')
16 ax1.set_title('% Sales per Participants By # of Engagement Types')
ValueError: Grouper for '<class 'pandas.core.frame.DataFrame'>' not 1-dimensional
Run Code Online (Sandbox Code Playgroud)
我试图搜索互联网和Stack Overflow这个错误,但没有得到任何结果.有谁知道发生了什么?
fir*_*ynx 48
我也遇到了这个问题,并找到了它的原因和明显的解决方案
要重新创建:
df = pd.DataFrame({"foo": [1,2,3], "bar": [1,2,3]})
df.rename(columns={'foo': 'bar'}, inplace=True)
bar bar
0 1 1
1 2 2
2 3 3
df.groupby('bar')
ValueError: Grouper for 'bar' not 1-dimensional
Run Code Online (Sandbox Code Playgroud)
就像许多神秘的熊猫错误一样,这个错误也源于两个具有相同名称的列.
确定要使用哪一个,重命名或删除另一个列并重做操作.
像这样重命名列
df.columns = ['foo', 'bar']
foo bar
0 1 1
1 2 2
2 3 3
df.groupby('bar')
<pandas.core.groupby.DataFrameGroupBy object at 0x1066dd950>
Run Code Online (Sandbox Code Playgroud)
有一些内容需要添加到 @wm 的答案中。
如果要将多个列从一个数据帧添加到另一个数据帧:
df1[['col1', 'col2']] = df2[['col1', 'col2']]
Run Code Online (Sandbox Code Playgroud)
它将创建一个多列索引,如果您尝试按 上的任何内容进行分组df1,则会出现此错误。
要解决此问题,请使用以下方法摆脱多索引
df1.columns = df1.columns.get_level_values(0)
Run Code Online (Sandbox Code Playgroud)
TL;DR:
简单的例子:如果我要按职业分组一群人,你要么是工程师,要么是技术,不能两者兼而有之,否则 groupby 不知道是把你放在技术组还是工程师组.
不幸的是,您的代码同时分配了一些人(一些indexes在您的 df 中)进入 eng AND tech。
groupby()。我们将使用这个示例水果df:
import pandas as pd
import numpy as np
df = pd.DataFrame(
{"fruit": ['apple', 'apple', 'orange', 'orange'], "color": ['r', 'g', 'b', 'r']},
index=[11, 22, 33, 44],
)
"""
[df] df:
+----+---------+---------+
| | fruit | color |
|----+---------+---------|
| 11 | apple | r |
| 22 | apple | g |
| 33 | orange | b |
| 44 | orange | r |
+----+---------+---------+
"""
Run Code Online (Sandbox Code Playgroud)
下面是一个非常有效的df.groupby(),不使用任何列名:
gp = df.groupby(
{
0: 'mine',
1: 'mine',
11: 'mine',
22: 'mine',
33: 'mine',
44: 'you are rats with wings!',
}
)
"""
[df] [group] mine:
+----+---------+---------+
| | fruit | color |
|----+---------+---------|
| 11 | apple | r |
| 22 | apple | g |
| 33 | orange | b |
+----+---------+---------+
[df] [group] you are rats with wings!:
+----+---------+---------+
| | fruit | color |
|----+---------+---------|
| 44 | orange | r |
+----+---------+---------+
"""
Run Code Online (Sandbox Code Playgroud)
等等,groupby()甚至根本没有使用“水果”或“颜色”?!
这是正确的!groupby()不需要关心df“水果”或“颜色”或Nemo,groupby()只关心一件事,一个查找表,告诉它哪个索引映射到哪个标签(即组)。
例如,在这种情况下,传递给 的字典groupby()指示groupby():
如果您看到 index 11,则它是 a "mine",将具有该索引的行放在名为 的组中"mine"。
如果您看到 index 22,则它是 a "mine",将具有该索引的行放入名为 的组中"mine"。
...
即使 0 和 1 不在里面df.index也不是问题
常规df.groupby('fruit')或df.groupby(df['fruit'])完全遵循上述规则。该列df['fruit']用作查找表,它告诉groupby()索引11是一个"apple"
它说的是真的: for some or all indexes in df, you are assigning MORE THAN just one label
让我们使用上面的示例检查一些可能的错误:
[x]df.groupby(df)不起作用,您给出了groupby()一个 2D 映射,每个索引被赋予了 2 个组名。它会抱怨:is index 11 an "apple" or an "r"? make up your mind!
[x] 下面的代码也不起作用。尽管映射现在是一维的,但它同时将索引映射11到"mine"以及"yours"。Pandasdf并sr允许非唯一索引,所以要小心。
mapping = pd.DataFrame(index= [ 11, 11, 22, 33, 44 ],
data = ['mine', 'yours', 'mine', 'mine', 'yours'], )
df.groupby(mapping)
# different error message, but same idea
mapping = pd.Series( index= [ 11, 11, 22, 33, 44 ],
data = ['mine', 'yours', 'mine', 'mine', 'yours'], )
df.groupby(mapping)
Run Code Online (Sandbox Code Playgroud)
当我不小心创建 MultiIndex 列时发生在我身上:
>>> values = np.asarray([[1, 1], [2, 2], [3, 3]])
# notice accidental double brackets around column list
>>> df = pd.DataFrame(values, columns=[["foo", "bar"]])
# prints very innocently
>>> df
foo bar
0 1 1
1 2 2
2 3 3
# but throws this error
>>> df.groupby("foo")
ValueError: Grouper for 'foo' not 1-dimensional
# cause:
>>> df.columns
MultiIndex(levels=[['bar', 'foo']],
labels=[[1, 0]])
# fix by using correct columns list
>>> df = pd.DataFrame(values, columns=["foo", "bar"])
>>> df.groupby("foo")
<pandas.core.groupby.groupby.DataFrameGroupBy object at 0x7f9a280cbb70>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26947 次 |
| 最近记录: |