pandas按行按列遍历Dataframe的三种方式

pandas遍历DataFrame主要有三种方式。

iterrows(): 按行遍历,将DataFrame的每一行迭代为(index, Series)对,可以通过row[name]对元素进行访问。
itertuples(): 按行遍历,将DataFrame的每一行迭代为元祖,可以通过row[name]对元素进行访问,比iterrows()效率高。
iteritems(): 按列遍历,将DataFrame的每一列迭代为(列名, Series)对,可以通过row[index]对元素进行访问。

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

for index, row in df.iterrows():
    print(index) # 输出每行的索引值
#output:
0
1
2

row['name']
# 对于每一行,通过列名name访问对应的元素
for row in df.iterrows():
    print(row['c1'], row['c2']) # 输出每一行

#output:
10  100
11  110
12  123
按行遍历interuples():
getattr(row, 'name')
for row in df.intertuples():
  print(getattr(row,'c1'), getattr(row,'c2')) #输出每一行
#output:
10  100
11  110
12  123
按列遍历interitems():
for index, row in df.interitems():
  print(index) #输出列明
#output:
c1
c2

for row in df.interitems():
  print(row[0], row[1], row[2]) #输出各列

output:
10   11   12
100  110  123

参考链接:
https://blog.csdn.net/sinat_29675423/article/details/87972498

本文链接:

https://ma.ge/archives/301.html
1 + 7 =
快来做第一个评论的人吧~