pandas-循环

  • iterrows(): 将DataFrame迭代为(insex, Series)对。
  • itertuples(): 将DataFrame迭代为元祖。
  • iteritems(): 将DataFrame迭代为(列名, Series)对
s = [{'a':10, 'b':100}, {'a':11, 'b':110}, {'a':12, 'b':123}]
df = pd.DataFrame(s)
df

    a	b
0	10	100
1	11	110
2	12	123

iterrows():

for i,r in df.iterrows():
    print(i)
    print("********************")
    print(r)


0
********************
a     10
b    100
Name: 0, dtype: int64
1
********************
a     11
b    110
Name: 1, dtype: int64
2
********************
a     12
b    123
Name: 2, dtype: int64

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

for i, r in df.iterrows():
    print(r['a'], r['b'])


10 100
11 110
12 123

itertuples()

for t in df.itertuples():
   
    print(t)
​
Pandas(Index=0, a=10, b=100)
Pandas(Index=1, a=11, b=110)
Pandas(Index=2, a=12, b=123)
for t in df.itertuples():
  
    print(getattr(t,'a'))

   
10
11
12
for t in df.itertuples():
  
    print(getattr(t,'a'),getattr(t,'b'))

10 100
11 110
12 123

iteritems()

for date, row in df.iteritems():
    print(date)
a
b
for date, row in df.iteritems():
    print(row[0], row[1], row[2])
10 11 12
100 110 123

https://www.cnblogs.com/selfcs/archive/2019/09/03/11451595.html

你可能感兴趣的:(Python,数据预处理)