有如下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
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
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
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