>>> from env_helper import info; info()
页面更新时间: 2023-07-09 19:02:24
运行环境:
Linux发行版本: Debian GNU/Linux 12 (bookworm)
操作系统内核: Linux-6.1.0-10-amd64-x86_64-with-glibc2.36
Python版本: 3.11.2
6.9. Pandas迭代¶
Pandas对象之间的基本迭代的行为取决于类型。当迭代一个系列时,它被视为数组式,基本迭代产生这些值。其他数据结构,如:DataFrame和Panel,遵循类似惯例迭代对象的键。
简而言之,基本迭代(对于i在对象中)产生 -
Series - 值
DataFrame - 列标签
Pannel - 项目标签
6.9.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
x
y
C
D
要遍历数据帧(DataFrame)中的行,可以使用以下函数 -
iteritems() - 迭代(key,value)对
iterrows() - 将行迭代为(索引,系列)对
itertuples() - 以namedtuples的形式迭代行
iteritems()示例¶
将每个列作为键,将值与值作为键和列值迭代为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)
col1 0 -0.554543
1 1.306994
2 -0.119159
3 0.047936
Name: col1, dtype: float64
col2 0 -0.719993
1 -0.136078
2 -0.792701
3 0.314983
Name: col2, dtype: float64
col3 0 0.563876
1 1.338024
2 0.033014
3 -0.783497
Name: col3, dtype: float64
/tmp/ipykernel_261070/2326545308.py:5: FutureWarning: iteritems is deprecated and will be removed in a future version. Use .items instead.
for key,value in df.iteritems():
观察一下,单独迭代每个列作为系列中的键值对。
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.489098
col2 -0.548872
col3 -1.094861
Name: 0, dtype: float64
1 col1 0.867153
col2 0.733335
col3 0.866252
Name: 1, dtype: float64
2 col1 -0.153927
col2 0.446232
col3 -0.730138
Name: 2, dtype: float64
3 col1 -2.110785
col2 0.204727
col3 -0.644052
Name: 3, dtype: float64
注意 - 由于iterrows()遍历行,因此不会跨该行保留数据类型。0,1,2是行索引,col1,col2,col3是列索引。
6.9.2. 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.4156123595565651, col2=2.26954802384536, col3=1.8573338018722616)
Pandas(Index=1, col1=0.9532170816254911, col2=0.8318068233854913, col3=-0.5291127336964973)
Pandas(Index=2, col1=-1.0663236143709856, col2=-0.1954324941525572, col3=1.4275514682765906)
Pandas(Index=3, col1=-1.5359605999520773, col2=-0.8999176242414509, col3=-0.3852118259330032)
注意 - 不要尝试在迭代时修改任何对象。迭代是用于读取,迭代器返回原始对象(视图)的副本,因此更改将不会反映在原始对象上。
示例代码¶
>>> 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 -0.370082 -1.612691 -0.112481
1 1.538205 0.589429 1.149983
2 -0.160714 1.522870 -0.901730
3 -0.439948 -0.435731 -1.244363
注意观察结果,修改变化并未反映出来。