在Pandas對象上進(jìn)行基本迭代的行為取決于類型。在Series上進(jìn)行迭代時(shí),它等同于數(shù)組。其他數(shù)據(jù)結(jié)構(gòu)(例如DataFrame和Panel)遵循類似dict的語法,即在對象的鍵上進(jìn)行迭代。
In short, basic iteration (for i in object) produces ?
Series ? 值 DataFrame ? 列標(biāo)簽 Panel ? item 標(biāo)簽
迭代DataFrame會給出列名。我們看看以下示例。
import pandas as pd import numpy as np N=20 df = pd.DataFrame({ 'A': pd.date_range(start='2016-01-01',periods=N,freq='D'), 'x': np.linspace(0,stop=N-1,num=N), 'y': np.random.rand(N), 'C': np.random.choice(['Low','Medium','High'],N).tolist(), 'D': np.random.normal(100, 10, size=(N)).tolist() }) for col in df: print col
其輸出如下
A C D x y
要遍歷DataFrame的行,我們可以使用以下函數(shù)-
iteritems() ? 迭代(鍵,值)對 iterrows() ? 以(index,series)對的形式遍歷行 itertuples() ? 以namedtuples的形式遍歷行
遍歷每列作為鍵,將帶有標(biāo)簽的值對作為鍵,將列值作為Series對象。
import pandas as pd import numpy as np df = pd. DataFrame(np. random.randn(4,3),columns=[ 'col1', 'col2', 'col3']) for key,value in df. iteritems(): print key,value
運(yùn)行結(jié)果:
col1 0 0.802390 1 0.324060 2 0.256811 3 0.839186 Name: col1, dtype: float64 col2 0 1.624313 1 -1.033582 2 1.796663 3 1.856277 Name: col2, dtype: float64 col3 0 -0.022142 1 -0.230820 2 1.160691 3 -0.830279 Name: col3, dtype: float64
可以看出每一列作為系列中的鍵值對分別進(jìn)行迭代。
iterrows() 返回產(chǎn)生每個(gè)索引值以及包含每一行數(shù)據(jù)的序列的迭代器。
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3']) for row_index,row in df.iterrows(): print row_index,row
運(yùn)行結(jié)果:
0 col1 1.529759 col2 0.762811 col3 -0.634691 Name: 0, dtype: float64 1 col1 -0.944087 col2 1.420919 col3 -0.507895 Name: 1, dtype: float64 2 col1 -0.077287 col2 -0.858556 col3 -0.663385 Name: 2, dtype: float64 3 col1 -1.638578 col2 0.059866 col3 0.493482 Name: 3, dtype: float64
由于iterrows()遍歷行,因此不會保留行中的數(shù)據(jù)類型。0,1,2是行索引,col1,col2,col3是列索引。
itertuples()方法將返回一個(gè)迭代器,為DataFrame中的每一行生成一個(gè)命名的元組。元組的第一個(gè)元素將是行的相應(yīng)索引值,而其余值是行值。
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3']) for row in df.itertuples(): print row
運(yùn)行結(jié)果:
Pandas(Index=0, col1=1.5297586201375899, col2=0.76281127433814944, col3=- 0.6346908238310438) Pandas(Index=1, col1=-0.94408735763808649, col2=1.4209186418359423, col3=- 0.50789517967096232) Pandas(Index=2, col1=-0.07728664756791935, col2=-0.85855574139699076, col3=- 0.6633852507207626) Pandas(Index=3, col1=0.65734942534106289, col2=-0.95057710432604969, col3=0.80344487462316527)
import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3']) for index, row in df.iterrows(): row['a'] = 10 print df
運(yùn)行結(jié)果:
col1 col2 col3 0 -1.739815 0.735595 -0.295589 1 0.635485 0.106803 1.527922 2 -0.939064 0.547095 0.038585 3 -1.016509 -0.116580 -0.523158
觀察,沒有反映出任何變化。