我希望能够通过多索引分组来迭代 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()
。
但是,大多数情况下不需要这样的迭代! process_row
需要什么?也许您可以直接在 groupby 对象上以矢量化方式执行此操作。
关于python - 在 python pandas 中迭代多索引数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27279879/