繁体   English   中英

在python熊猫中遍历MultiIndex数据

[英]Iterating through MultiIndex data in python pandas

我希望能够通过对多索引进行分组来遍历pandas DataFrame。 在这里,我希望能够一起处理每个行业中的一组行。 我加载了多索引。

from StringIO import StringIO
data = """industry,location,number
retail,brazil,294
technology,china,100
retail,nyc,2913
retail,paris,382
technology,us,2182
"""

df = pd.read_csv(StringIO(data), sep=",", index_col=['industry', 'location'])

所以我希望能有一些效果:

for industry, rows in df.iter_multiindex():
    for row in rows:
        process_row(row)

有这种方法吗?

您可以按多索引的第一级(行业)分组,然后遍历各组:

In [102]: for name, group in df.groupby(level='industry'):
   .....:     print name, '\n', group, '\n'
   .....:
retail
                   number
industry location
retail   brazil       294
         nyc         2913
         paris        382

technology
                     number
industry   location
technology china        100
           us          2182

group每次是一个数据框,然后可以遍历该数据for row in group.iterrows()例如, for row in group.iterrows()

但是 ,在大多数情况下,不需要这种迭代! process_row需要什么? 可能您可以直接在groupby对象上以矢量化方式执行此操作。

不确定为什么要这样做,但是可以这样:

for x in df.index:
    print x[0] # industry
    process(df.loc[x]) # row

但这不是您通常使用DataFrame的方式,您可能想阅读有关apply()Essential Basic Functionality也很有帮助)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM