目录设定
- 迭代DataFrame
- 迭代DataFrame - 遍历数据帧
- iteritems()示例
- iterrows()示例
- itertuples()示例
重磅!今天给大家拿到Python的核心资料!实实在在在工业界会要用到!公众号后台回复“Python数据科学”全部获取得到!
Pandas对象之间的基本迭代的行为取决于类型。当迭代一个系列时,它被视为数组式,基本迭代产生这些值
注意: 不要尝试在迭代时修改任何对象。迭代是用于读取,迭代器返回原始对象(视图)的副本,因此更改将不会反映在原始对象上。
迭代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)
res:
A
C
D
x
迭代DataFrame - 遍历数据帧
迭代器 | details | 备注 |
iteritems() | 将列迭代(col,value)对 | 列值 |
iterrows() | 将行迭代(index,value)对 | 行值 |
itertuples() | 以namedtuples的形式迭代行 | 行pandas形式 |
iteritems()示例
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4,3),columns=['col1','col2','col3'])
print df
for key,value in df.iteritems():
print (key,value)
结果:
col1 col2 col3
0 2.040860 3.054064 0.294766
1 -0.545032 0.484716 -0.127386
2 -0.647270 0.246625 -1.215398
3 1.236336 0.945946 -1.313925
<========================================
('col1', 0 2.040860
1 -0.545032
2 -0.647270
3 1.236336
Name: col1, dtype: float64)
('col2', 0 3.054064
1 0.484716
2 0.246625
3 0.945946
Name: col2, dtype: float64)
('col3', 0 0.294766
1 -0.127386
2 -1.215398
3 -1.313925
Name: col3, dtype: float64)
iterrows()示例
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])
print df
for row_index,row in df.iterrows():
print (row_index,row)
结果:
col1 col2 col3
0 1.317360 0.209008 -1.406420
1 -1.410877 0.549579 0.114726
2 -0.625855 0.759171 1.128685
3 -0.726843 0.936854 -0.088602
<===================================
(0, col1 1.317360
col2 0.209008
col3 -1.406420
Name: 0, dtype: float64)
(1, col1 -1.410877
col2 0.549579
col3 0.114726
Name: 1, dtype: float64)
(2, col1 -0.625855
col2 0.759171
col3 1.128685
Name: 2, dtype: float64)
(3, col1 -0.726843
col2 0.936854
col3 -0.088602
Name: 3, dtype: float64)
itertuples()示例
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(4,3),columns = ['col1','col2','col3'])
print df
for row in df.itertuples():
print (row)
结果:
col1 col2 col3
0 2.344358 0.995072 -0.854100
1 -1.753913 0.116023 -0.695364
2 0.683273 -1.420054 -1.135608
3 0.704008 -0.805667 -1.470546
<==========================================
Pandas(Index=0, col1=2.344358114509865, col2=0.9950716436632336, col3=-0.8540998901850537)
Pandas(Index=1, col1=-1.753912851201583, col2=0.11602289315026405, col3=-0.6953643685628161)
Pandas(Index=2, col1=0.6832726480890194, col2=-1.4200541327635743, col3=-1.1356075254300841)
Pandas(Index=3, col1=0.7040080214990596, col2=-0.8056672789772055, col3=-1.4705455721132779)
今天给大家拿到Python的核心资料!实实在在在工业界会要用到!公众号后台回复“Python数据科学”全部获取得到!