pandas.DataFrame 按行和列遍历DataFrame

 

Python:3.8.5

pandas:1.1.3

 

​​​​​​按行遍历DataFrame:

按列遍历DataFrame:

测试用例:

import pandas as pd
test = pd.DataFrame(columns = ['first', 'second', 'third'])
for i in range(10):
    test.loc[i] = [i, i + 1, i + 2]

#-------------------------------------------------------
‘’‘ 测试用例
   first second third
0      0      1     2
1      1      2     3
2      2      3     4
3      3      4     5
4      4      5     6
5      5      6     7
6      6      7     8
7      7      8     9
8      8      9    10
’‘’

按行遍历 —— iterrows()

以(index, Series)对的形式迭代DataFrame行。

for index, row in test.iterrows():
    print(index) # 输出每一行的索引
# 此处的index数据类型为 int
# 此处的row数据类型为 pandas.core.series.Series

for index, row in test.iterrows():
    print(row['first'], row['third']) # 输出每一行的‘first’与‘second’的值
# 此处的row['first']数据类型为 int

for row in test.iterrows():
    print(row) # 输出所有数据
# 此处的row数据类型为 tuple

循环中可以通过‘变量名[’列名‘]’的形式访问每一行中的对应列的值

按行遍历 —— itertuples()

以命名元组的形式遍历DataFrame行。

for row in test.itertuples():
    print(getattr(row, 'Index')) # 输出每一行的索引
# 此处的getattr(row, 'Index')数据类型 int
# 此处的row数据类型为 pandas.core.frame.Pandas

for row in test.itertuples():
    print(getattr(row, 'first'), getattr(row, 'third')) # 输出每一行的‘first’与‘third’的值
# 此处的getattr(row, 'first')数据类型为 int
# 此处的row数据类型为 pandas.core.frame.Pandas

按列遍历 —— items()

遍历DataFrame列,返回一个具有列名和内容为Series的元组。

for columnName, column in test.items():
    print(columnName) # 输出列名,这里是输出 ’first‘, ’second‘,  ’third‘
# 此处的columnName的数据类型为 str

for i, column in test.items():
    print(column) # 输出每一列的元素,每一列都是一个Series的对象
# 此处的column的数据类型为 pandas.core.series.Series

for i, column in test.items():
    print(column[2:7]) # 输出每一列第2到第6个数据
# 此处column[x:y]的数据类型为 pandas.core.series.Series

按列遍历 —— iteritems()

遍历DataFrame列,返回一个具有列名和内容为Series的元组。

for name, column in test.iteritems():
    print(i) # 输出列名
#此处的name数据类型为 str

for name, column in test.iteritems():
    print(column[1]) # 输出第一行的数据
#此处column[x]的数据类型为 int

for name, column in test.iteritems():
    print(column[2:7]) # 输出每一列第2到第6个数据
#此处column[x:y]的数据类型为 pandas.core.series.Series

 

  • 4
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值