Python 如何使石斑鱼和轴的长度相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19483991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make grouper and axis the same length?
提问by mikez1
For my assignment I'm supposed to plot the tracks of 20 hurricanes on a map using matplotlib. However when I run my code I get the error: AssertionError:Grouper and axis must be the same length
对于我的作业,我应该使用 matplotlib 在地图上绘制 20 次飓风的轨迹。但是,当我运行代码时,出现错误:AssertionError:Grouper and axis must be the same length
Here's the code I have:
这是我的代码:
import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from PIL import *
fig = plt.figure(figsize=(12,12))
ax = fig.add_axes([0.1,0.1,0.8,0.8])
m = Basemap(llcrnrlon=-100.,llcrnrlat=0.,urcrnrlon=-20.,urcrnrlat=57.,
projection='lcc',lat_1=20.,lat_2=40.,lon_0=-60.,
resolution ='l',area_thresh=1000.)
m.bluemarble()
m.drawcoastlines(linewidth=0.5)
m.drawcountries(linewidth=0.5)
m.drawstates(linewidth=0.5)
# Creates parallels and meridians
m.drawparallels(np.arange(10.,35.,5.),labels=[1,0,0,1])
m.drawmeridians(np.arange(-120.,-80.,5.),labels=[1,0,0,1])
m.drawmapboundary(fill_color='aqua')
# Opens data file
import pandas as pd
name = [ ]
df = pd.read_csv('louisianastormb.csv')
for name, group in df.groupby([name]):
latitude = group.lat.values
longitude = group.lon.values
x,y = m(longitude, latitude)
plt.plot(x,y,'y-',linewidth=2 )
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('20 Hurricanes with Landfall in Louisiana')
plt.savefig('20hurpaths.jpg', dpi=100)
Here's the full error output:
这是完整的错误输出:
Traceback (most recent call last):
File "/home/darealmzd/lstorms.py", line 31, in <module>
for name, group in df.groupby([name]):
File "/usr/local/lib/python2.7/dist-packages/pandas/core/generic.py", line 186, in groupby
squeeze=squeeze)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 533, in groupby
return klass(obj, by, **kwds)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 197, in __init__
level=level, sort=sort)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 1325, in _get_grouper
ping = Grouping(group_axis, gpr, name=name, level=level, sort=sort)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 1129, in __init__
self.grouper = _convert_grouper(index, grouper)
File "/usr/local/lib/python2.7/dist-packages/pandas/core/groupby.py", line 1350, in _convert_grouper
raise Assertionerror('Grouper and axis must be same length')
Assertionerror: Grouper and axis must be same length
采纳答案by Jeff Tratner
The problem is that you're grouping by (effectively) a list of empty list ([[]]
). Because you have name = []
earlier and then you wrap that in a list as well.
问题是您正在按(有效地)空列表 ( [[]]
)的列表进行分组。因为你name = []
之前有,然后你也把它包装在一个列表中。
If you want to group on a single column (called 'HurricaneName'), you should do something like:
如果您想对单个列(称为“HurricaneName”)进行分组,您应该执行以下操作:
for name, group in df.groupby('HurricaneName'):
for name, group in df.groupby('HurricaneName'):
However, if you want to group on multiple columns, then you need to pass a list:
但是,如果要对多个列进行分组,则需要传递一个列表:
for name, group in df.groupby(['HurricaneName', 'Year'])
for name, group in df.groupby(['HurricaneName', 'Year'])
If you want to put it in a variable like you have, you can do it like this:
如果你想把它放在一个像你一样的变量中,你可以这样做:
col_name = 'State'
for name, group in df.groupby([col_name]):
回答by Corey Levinson
ValueError: Grouper and axis must be same length
ValueError: Grouper and axis must be same length
This can occur if you are using double brackets in the groupby
argument.
如果您在groupby
参数中使用双括号,就会发生这种情况。
(I posted this since it is the top result on Google).
(我发布了这个,因为它是谷歌上的最高结果)。
回答by Subhodeep Sinha
Try iloc to make grouper equal to axis.
尝试 iloc 使石斑鱼等于轴。
example: sns.boxplot(x=df['pH-binned'].iloc[0:3], y=v_count, data=df)
示例:sns.boxplot(x=df['pH-binned'].iloc[0:3], y=v_count, data=df)
In case axis=3.
如果轴 = 3。