Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 熊猫-根据groupby索引级别绘制_Python_Pandas_Matplotlib - Fatal编程技术网

Python 熊猫-根据groupby索引级别绘制

Python 熊猫-根据groupby索引级别绘制,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个简单的数据帧df: City,H AMS,1.1 AMS,0.8 AMS,0.9 BOS,0.9 BOS,0.7 BOS,0.6 BOS,0.8 我想根据每个城市对H列进行排序,然后用不同的颜色绘制每个城市索引。到目前为止,我从分组和排序开始: d = df.groupby('City').apply(lambda x: x.sort('H', ascending=False)) 然后,由于我想根据排序绘制每个城市的H值,我添加了一个名为subindex的列,如下所示: d['sub

我有一个简单的数据帧
df

City,H
AMS,1.1
AMS,0.8
AMS,0.9
BOS,0.9
BOS,0.7
BOS,0.6
BOS,0.8
我想根据每个
城市
H
列进行排序,然后用不同的颜色绘制每个
城市
索引。到目前为止,我从分组和排序开始:

d = df.groupby('City').apply(lambda x: x.sort('H', ascending=False))
然后,由于我想根据排序绘制每个城市的
H
值,我添加了一个名为
subindex
的列,如下所示:

d['subindex'] = d.groupby(level=0).cumcount() + 1
生成的数据帧是:

       City    H  subindex
City                      
AMS  0  AMS  1.1         1
     2  AMS  0.9         2
     1  AMS  0.8         3
BOS  3  BOS  0.9         1
     6  BOS  0.8         2
     4  BOS  0.7         3
     5  BOS  0.6         4
格式是我想要的,但我不明白为什么列
City
出现两次。现在的问题是,对于每个
城市
,根据
子索引
绘制
H
值。我试过:

for i, group in d:
    group.plot(x='subindex', y='H')
接收以下
ValueError

for i, group in d:
ValueError: too many values to unpack

您的
d
不再是
groupby
对象,而是一个多索引的df,这就是您得到错误的原因:

In [61]:
for col in d:
    print(col)

City
H
subindex
这就是现在的
d

Out[52]:
       City    H  subindex
City                      
AMS  0  AMS  1.1         1
     2  AMS  0.9         2
     1  AMS  0.8         3
BOS  3  BOS  0.9         1
     6  BOS  0.8         2
     4  BOS  0.7         3
     5  BOS  0.6         4
如果未在
groupby
对象上调用
apply
,则可以访问

In [69]:
g = df.groupby('City')
g.groups

Out[69]:
{'AMS': [0, 1, 2], 'BOS': [3, 4, 5, 6]}
您可以像以前一样正确地迭代
groupby
对象:

In [71]:
for i, group in g:
    print(i)
    print(group)

AMS
  City    H
0  AMS  1.1
1  AMS  0.8
2  AMS  0.9
BOS
  City    H
3  BOS  0.9
4  BOS  0.7
5  BOS  0.6
6  BOS  0.8
因此,您现在要做的是使用索引级别过滤df并绘制它们:

for city in d.index.get_level_values(0).unique():
    d[d['City']==city].plot(x='subindex', y='H')
产量如下:


从df返回的iterable是列,您的df不再是
groupby
而是多索引df,因此您需要
d.index.get_level_值(0).unique()