Pandas 迭代数据帧的“条目”

Pandas 迭代数据帧的“条目”,pandas,dataframe,Pandas,Dataframe,假设我有一个潜在的多索引,但可能不是数据帧。例如: iterables = [['foo', 'bar'], ['one', 'two']] idx = pd.MultiIndex.from_product(iterables, names=['first', 'second']) df = pd.DataFrame(np.random.randn(4, 2), index=idx, columns=('metric1', 'metric2')) 结果: metr

假设我有一个潜在的多索引,但可能不是数据帧。例如:

iterables = [['foo', 'bar'], ['one', 'two']]
idx = pd.MultiIndex.from_product(iterables, names=['first', 'second'])
df = pd.DataFrame(np.random.randn(4, 2), index=idx, columns=('metric1', 'metric2'))
结果:

               metric1   metric2
first second                    
foo   one     0.189589  0.787533
      two     0.176290 -0.080153
bar   one     0.077977 -0.384613
      two     0.658583  0.436177
有许多方法可以迭代此数据帧中的每个元素,但大多数方法都涉及两个嵌套for循环,如:

for r in df.index:
    for c in df.columns:
        print r, c, df.loc[r,c]
产生

('foo', 'one') metric1 -0.00381142017312
('foo', 'one') metric2 -0.755465118408
('foo', 'two') metric1 0.444271742766
('foo', 'two') metric2 0.18390288873
('bar', 'one') metric1 0.512679930964
('bar', 'one') metric2 -0.134535924251
('bar', 'two') metric1 1.93222192752
('bar', 'two') metric2 0.609813960012

是否有一种方法可以在一个循环中实现这一点,以便在迭代时可以访问每个元素的行名称和列名?如果只能使用常规索引,我仍然感兴趣。

您可以将数据帧堆叠为一个系列,然后一次性循环:

for ind, val in df.stack().items():
    print(ind, val)

('foo', 'one', 'metric1') -0.752747101421
('foo', 'one', 'metric2') 0.318196702146
('foo', 'two', 'metric1') -0.737599211438
('foo', 'two', 'metric2') -1.08364260415
('bar', 'one', 'metric1') 1.87757917778
('bar', 'one', 'metric2') -2.29588862481
('bar', 'two', 'metric1') -0.301414352794
('bar', 'two', 'metric2') 0.610076176389