扫码一下
查看教程更方便
pandas 对象的基本迭代行为取决于要进行迭代的数据的类型。当迭代一个 series 数据时,它被视为一个一维数组,基本迭代出来的是个值。而对于其他数据结构,如 dataframe 和 panel,要看其容器内值的数据类型。
下面我们通过示例来实际看一下迭代数据。因为 dataframe 数据使用最广泛,所以我们这里以迭代 dataframe 为例来介绍。
迭代 dataframe 会给出列名。我们看下面的代码
import pandas as pd
import numpy as np
n=20
df = pd.dataframe({
'a': pd.date_range(start='20121-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
x
y
c
d
要对 dataframe 迭代的话,我们有三个方法可以使用:iteritems()、iterrows() 和 itertuples()。下面我们分别看一下这三个函数的使用
iteritems()方法对dataframe的列进行迭代,返回每一列的列标签和该列的值(series 或者 dataframe)。
import pandas as pd
import numpy as np
df = pd.dataframe(np.random.randn(4,3),columns=['col1','col2','col3'])
print("dataframe data:")
print(df)
print("iteration data:")
for key,value in df.iteritems():
print(key ":")
print(value)
运行结果如下
dataframe data:
col1 col2 col3
0 -0.819946 0.579416 -0.627961
1 -0.065043 -0.012912 -0.615037
2 -1.376036 -0.213219 1.474679
3 1.474267 -0.393431 1.352231
iteration data:
col1:
0 -0.819946
1 -0.065043
2 -1.376036
3 1.474267
name: col1, dtype: float64
col2:
0 0.579416
1 -0.012912
2 -0.213219
3 -0.393431
name: col2, dtype: float64
col3:
0 -0.627961
1 -0.615037
2 1.474679
3 1.352231
name: col3, dtype: float64
通过对数据进行对比,我们可以看到 iteritems() 遍历的方式。每一次返回列标签和该列的数据。
iterrows() 对dataframe的行进行迭代。该函数会对 dataframe 数据的每一行进行遍历按,返回行索引标签和该行的数据。
import pandas as pd
import numpy as np
df = pd.dataframe(np.random.randn(4,3),columns=['col1','col2','col3'])
print("dataframe data:")
print(df)
print("iteration data:")
for key,value in df.iterrows():
print(key,":")
print(value)
运行结果如下
dataframe data:
col1 col2 col3
0 0.325120 1.648155 -0.919671
1 0.491986 -0.869964 -0.868903
2 0.326004 0.506313 -0.429626
3 0.270518 0.896477 -1.390016
iteration data:
0 :
col1 0.325120
col2 1.648155
col3 -0.919671
name: 0, dtype: float64
1 :
col1 0.491986
col2 -0.869964
col3 -0.868903
name: 1, dtype: float64
2 :
col1 0.326004
col2 0.506313
col3 -0.429626
name: 2, dtype: float64
3 :
col1 0.270518
col2 0.896477
col3 -1.390016
name: 3, dtype: float64
注意- 因为iterrows()是对行进行遍历,所以它不会跨行保留数据类型。0,1,2 是行索引,col1,col2,col3 是列索引。
itertuples() 方法将返回一个迭代器,它会对dataframe中的数据的每一行进行遍历,为每一行生成一个命名元组。元组的第一个元素将是行对应的索引值,而其余值是行值。
import pandas as pd
import numpy as np
df = pd.dataframe(np.random.randn(4,3),columns = ['col1','col2','col3'])
print("dataframe data:")
print(df)
print("iteration data:")
for row in df.itertuples():
print(row)
运行结果如下
dataframe data:
col1 col2 col3
0 -0.297894 -2.924375 0.493184
1 -0.152143 1.362161 -1.227777
2 0.306161 0.901222 -1.041347
3 -1.311786 -0.550580 -0.937523
iteration data:
pandas(index=0, col1=-0.29789431085630064, col2=-2.924375322639692, col3=0.493183862759637)
pandas(index=1, col1=-0.15214278676213566, col2=1.3621605982781764, col3=-1.2277774006114013)
pandas(index=2, col1=0.30616074713169544, col2=0.9012222959685016, col3=-1.0413472932448207)
pandas(index=3, col1=-1.3117864713591012, col2=-0.5505795859827414, col3=-0.9375227129803021)
注意- 不要在迭代时尝试修改任何对象。迭代只是用于读取数据,迭代器返回的只是原始对象(视图)的一个副本,因此在迭代器中的更改不会反映在原始对象上。
import pandas as pd
import numpy as np
df = pd.dataframe(np.random.randn(4,3),columns = ['col1','col2','col3'])
print("dataframe data:")
print(df)
for index, row in df.iterrows():
row['a'] = 10
print("modified data:")
print(df)
运行结果如下
dataframe data:
col1 col2 col3
0 -0.887119 0.073956 0.511210
1 -0.980788 -0.489913 0.967435
2 -0.481731 -1.472479 -0.077585
3 0.814361 0.507259 -0.131690
modified data:
col1 col2 col3
0 -0.887119 0.073956 0.511210
1 -0.980788 -0.489913 0.967435
2 -0.481731 -1.472479 -0.077585
3 0.814361 0.507259 -0.131690