时间:2021-07-02 08:57:13 | 栏目:Python代码 | 点击:次
遍历数据有以下三种方法:

简单对上面三种方法进行说明:
示例数据
import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11, 'c2':110}, {'c1':12, 'c2':123}]
df = pd.DataFrame(inp)
print(df)

按行遍历iterrows():
for index, row in df.iterrows(): print(index) # 输出每行的索引值

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

按行遍历itertuples():
getattr(row, ‘name')
for row in df.itertuples(): print(getattr(row, 'c1'), getattr(row, 'c2')) # 输出每一行

按列遍历iteritems():
for index, row in df.iteritems(): print(index) # 输出列名

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