在python中迭代多索引数据
我希望能够通过在多索引上分组来迭代熊猫数据帧。在这里,我希望能够一起处理每个行业中的一组行。我使用多索引加载在python中迭代多索引数据,python,csv,pandas,hierarchical-data,Python,Csv,Pandas,Hierarchical Data,我希望能够通过在多索引上分组来迭代熊猫数据帧。在这里,我希望能够一起处理每个行业中的一组行。我使用多索引加载 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), s
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)
有这样的方法吗?不确定为什么要这样做,但可以这样做:
for x in df.index:
print x[0] # industry
process(df.loc[x]) # row
但这不是您通常使用DataFrame的方式,您可能想了解(也非常有用)您可以按多索引的第一级(行业)进行分组,然后通过分组进行迭代:
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
每次都是一个数据帧,然后您可以对该数据帧进行迭代(例如对group.iterrows()中的行使用)
但是,在大多数情况下,这样的迭代是不需要的。处理行
需要什么?也许你可以直接在groupby对象上以矢量化的方式来做。我想看看关于-1原因的一些评论