[1146]python函数之iterrows(), iteritems(), itertuples()对dataframe进行遍历

  • iterrows(): 将DataFrame迭代为(insex, Series)对。
  • itertuples(): 将DataFrame迭代为元祖。
  • iteritems(): 将DataFrame迭代为(列名, Series)对

有如下DataFrame数据

import pandas as pd
 
inp = [{'c1':10, 'c2':100}, {'c1':11, 'c2':110}, {'c1':12, 'c2':123}]
df = pd.DataFrame(inp)
 
print(df)

# 输出
   c1   c2
0  10  100
1  11  110
2  12  123

1、iterrows()

for date, row in df.iterrows():
    print(date)

输出

0
1
2
for date, row in df.iterrows():
    print(row)

输出

c1     10
c2    100
Name: 0, dtype: int64
c1     11
c2    110
Name: 1, dtype: int64
c1     12
c2    123
Name: 2, dtype: int64

对于每一行,通过列名访问对应的元素

for date, row in df.iterrows():
    print(row['c1'], row['c2'])

输出

10 100
11 110
12 123

2、iteritems()

for date, row in df.iteritems():
    print(date)

输出

c1
c2
for date, row in df.iteritems():
    print(row)

输出

0    10
1    11
2    12
Name: c1, dtype: int64
0    100
1    110
2    123
Name: c2, dtype: int64
for date, row in df.iteritems():
    print(row[0], row[1], row[2])

输出

10 11 12
100 110 123

3、itertuples()

for row in df.itertuples():
 print(row)

输出

Pandas(Index=0, c1=10, c2=100)
Pandas(Index=1, c1=11, c2=110)
Pandas(Index=2, c1=12, c2=123)
for row in df.itertuples():
    print(getattr(row, 'c1'), getattr(row, 'c2'))

输出

10 100
11 110
12 123

参考:https://blog.csdn.net/likeyou1314918273/article/details/89514038

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周小董

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值