Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情。
在对 DataFrame 进行操作时,我们不可避免的需要逐行查看或操作数据,这篇文章就来介绍 Dataframe 数据的遍历。
试题:如何遍历 DataFrame 数据?
(难度:medium)
分析
由于 Dataframe 数据结构属于可迭代对象,因此可以使用for...in...
语句对 Dataframe 进行迭代,结果是列的名称,例如对下面数据进行迭代:
students = {'id':[1,2,3,4,5], 'name':['one','two','three','four','five'], 'score':[90,88,89,65,95], 'class':[1,1,2,2,3]}
df = pd.DataFrame(students)
df
复制代码
for i in df:
print(i)
复制代码
结果输出为:
id
name
score
class
复制代码
如果要迭代DataFrame的行,可以使用以下方法:
iteritems()
:遍历列 为(col, value)对iterrows()
: 遍历行 为(index, value)对itertuples()
:以namedtuples
形式遍历行
具体使用方法如下:
iteritems()
:
按列进行遍历,将列名作为键,把每列的列值作为 Series 对象。
for key, value in df.iteritems():
print(key)
print(value)
复制代码
结果输出为:
id
0 1
1 2
2 3
3 4
4 5
Name: id, dtype: int64
name
0 one
1 two
2 three
3 four
4 five
Name: name, dtype: object
score
0 90
1 88
2 89
3 65
4 95
Name: score, dtype: int64
class
0 1
1 1
2 2
3 2
4 3
Name: class, dtype: int64
复制代码
iterrows()
:按 index 逐行进行遍历,将每行作为 Series
对象。
for index, row in df.iterrows():
print(index)
print(row)
复制代码
结果输出为:
0
id 1
name one
score 90
class 1
Name: 0, dtype: object
1
id 2
name two
score 88
class 1
Name: 1, dtype: object
2
id 3
name three
score 89
class 2
Name: 2, dtype: object
3
id 4
name four
score 65
class 2
Name: 3, dtype: object
4
id 5
name five
score 95
class 3
Name: 4, dtype: object
复制代码
itertuples()
:为 DataFrame 中的每一行生成一个命名元组,元组的第一个元素为行索引值,其余值是行值。
for row in df.itertuples():
print(row)
复制代码
结果输出为:
Pandas(Index=0, id=1, name='one', score=90, _4=1)
Pandas(Index=1, id=2, name='two', score=88, _4=1)
Pandas(Index=2, id=3, name='three', score=89, _4=2)
Pandas(Index=3, id=4, name='four', score=65, _4=2)
Pandas(Index=4, id=5, name='five', score=95, _4=3)
复制代码
原创不易,如果小伙伴们觉得有帮助,麻烦点个赞再走呗~
最后,感谢女朋友在工作和生活中的包容、理解与支持 !
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END