1、Pandas 迭代
在Pandas对象上进行基本迭代的行为取决于类型。在Series上进行迭代时,它等同于数组。其他数据结构(例如DataFrame和Panel)遵循类似dict的语法,即在对象的键上进行迭代。
In short, basic iteration (for i in object) produces −
Series − 值
DataFrame − 列标签
Panel − item 标签
1.1、DataFrame迭代
迭代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的行,我们可以使用以下函数-
iteritems() − 迭代(键,值)对
iterrows() − 以(index,series)对的形式遍历行
itertuples() − 以namedtuples的形式遍历行
1.2、iterrows()
iterrows() 返回产生每个索引值以及包含每一行数据的序列的迭代器。
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)
运行结果:
0 col1 0.875161
col2 0.144342
col3 0.664736
Name: 0, dtype: float64
1 col1 1.180224
col2 0.726884
col3 0.878448
Name: 1, dtype: float64
2 col1 0.568181
col2 -0.796529
col3 0.238724
Name: 2, dtype: float64
3 col1 -2.145986
col2 0.274230
col3 1.567189
Name: 3, dtype: float64
由于iterrows()遍历行,因此不会保留行中的数据类型。0,1,2是行索引,col1,col2,col3是列索引。
1.3、itertuples()
itertuples()方法将返回一个迭代器,为DataFrame中的每一行生成一个命名的元组。元组的第一个元素将是行的相应索引值,而其余值是行值。
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)
运行结果:
Pandas(Index=0, col1=-0.8113389382605866, col2=0.3853638134237451, col3=-0.3302657609404103)
Pandas(Index=1, col1=1.4495965257950345, col2=0.2680574476193087, col3=0.26241417724984933)
Pandas(Index=2, col1=-0.9494596207815267, col2=-0.6541357923169907, col3=1.301280239525732)
Pandas(Index=3, col1=0.08978045904814608, col2=0.18449641246278978, col3=0.08105422446737164)
注意:请勿在迭代时尝试修改任何对象。迭代用于读取,迭代器返回原始对象(视图)的副本,因此更改不会反映在原始对象上。
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)
运行结果
col1 col2 col3
0 1.617542 -0.622969 -1.088180
1 1.671075 -1.239073 0.637613
2 0.097658 0.453944 -0.557526
3 0.482258 -0.391962 0.565231