一、介紹
Pandas
的基礎結構分為兩種:
- 數據框 DataFrame
- 序列 Series
數據框(DataFame)是擁有軸標簽的二維鏈表,類似於 Excel 中的行列關系。
列標簽為列名,行標簽為索引。
iterrows()
是在數據框中的行進行迭代的一個生成器,返回每行的索引以及一個包含行本身的對象。
二、實操
建立測試數據集。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'a': range(5),
'b': list('abcde'),
'c': np.random.randn(5),
'd': np.random.randn(5),
'e': np.random.randn(5)
})
df
'''
a b c d e
0 0 a -0.132885 0.565630 -0.837642
1 1 b -0.290722 2.363767 -0.581337
2 2 c 0.919731 -0.191452 -0.109648
3 3 d -0.509702 -2.129329 0.419094
4 4 e -0.041131 -0.672666 0.784658
'''
行遍歷測試。
# 行遍歷
for index, row in df.iterrows():
print(index)
print(row)
'''
0
a 0
b a
c -0.132885
d 0.56563
e -0.837642
Name: 0, dtype: object
1
a 1
b b
c -0.290722
d 2.36377
e -0.581337
Name: 1, dtype: object
'''
iterrows()
返回值為元組 (index, row)
。