遍历DataFrame的三种方法
- iteritem()方法返回一个
数据,可利用for循环获得输出 - iterrow()方法返回一个
数据,可利用for循环获得输出 itertuple()方法返回一个
数据,可利用getattr(row,‘列索引’)方法获得对应数据 按列遍历
column_indexs = []
for column_index, row_data in frame.iteritems():
column_indexs.append(column_index)
print(row_data)
print(column_indexs)
运行结果
0 Ohio
1 Ohio
2 Ohio
3 Nevada
4 Nevada
5 Nevada
Name: state, dtype: object
0 2000
1 2001
2 2002
3 2003
4 2004
5 2005
Name: year, dtype: int64
0 1.5
1 1.7
2 3.6
3 2.4
4 2.9
5 3.2
Name: pop, dtype: float64
['state', 'year', 'pop']
按行遍历
方法一:
row_indexs = []
for index, row in frame.iterrows():
row_indexs.append(index)
print(row['pop'])
print(row)
print(row_indexs)
运行结果
state Ohio
year 2000
pop 1.5
Name: 0, dtype: object
state Ohio
year 2001
pop 1.7
Name: 1, dtype: object
state Ohio
year 2002
pop 3.6
Name: 2, dtype: object
state Nevada
year 2003
pop 2.4
Name: 3, dtype: object
state Nevada
year 2004
pop 2.9
Name: 4, dtype: object
state Nevada
year 2005
pop 3.2
Name: 5, dtype: object
[0, 1, 2, 3, 4, 5]
方法二:
for row in frame.itertuples():
print(getattr(row, 'state'), getattr(row, 'year'), getattr(row, 'pop'))
print(type(row))
Ohio 2000 1.5
<class 'pandas.core.frame.Pandas'>
......
Nevada 2005 3.2
<class 'pandas.core.frame.Pandas'>
获取某个值
DataFrame.at[行索引,列索引]获取某一个值:
print(frame.at[1,'pop'])
DataFrame.iat[默认行索引,默认列索引]获取某一个值:
print(frame.iat[1,1])