赞
踩
前言:本博客转载自《DataFrame数据的多种遍历方法》
之前本人博客链接
《Python开发之Pandas的简单使用(一)》
《Python开发之Pandas的简单使用(二)》
《Python开发之处理常见的txt、excel、csv文档》
data = {'state':['Ohio','Ohio','Ohio','Nevada','Nevada','Nevada'],
'year':[2000,2001,2002,2003,2004,2005],
'pop':[1.5,1.7,3.6,2.4,2.9,3.2]}
frame = pd.DataFrame(data)
column_indexs = []
for column_index, row_data in frame.iteritems():
column_indexs.append(column_index)
print(row_data)
print(column_indexs)
运行结果:
row_indexs = []
for index, row in frame.iterrows():
row_indexs.append(index)
print(row)
print(row_indexs)
运行结果:
还可以通过列名获取对应数据
for index, row in frame.iterrows():
print(row['pop'])
运行结果:
for row in frame.itertuples():
print(getattr(row, 'state'), getattr(row, 'year'), getattr(row, 'pop'))
print(type(row))
运行结果:
演示数据准备
data = {'state':['Ohio','Ohio','Ohio','Nevada','Nevada','Nevada'],
'year':[2000,2001,2002,2003,2004,2005],
'pop':[1.5,1.7,3.6,2.4,2.9,3.2]}
frame = pd.DataFrame(data)
print(frame.columns)
for index in frame.index:
print(frame['state'].get(index))
运行结果:
与上面等价的两种写法
# 第一种
for index in frame.index:
print(frame['state'][index])
# 第二种
for index in frame.index:
print(frame.get('state').get(index))
print(frame.index)
for column in frame.columns:
print(frame[column].get(0))
运行结果:
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。