pandas遍历每一行
这里没有人问过这个具体的问题:
我想要遍历一个数据表(dataframe)中的每一行。具体来说,我想在每一行中通过列名来调用数据。有没有办法做到这一点?如果有的话,请给个示范。
我知道可以用 df[<列名>][<索引名>]
这种方式,但我觉得这并不能解决我的问题。也许我可以把这个和转置功能结合起来,但那样的话我就会搞不清楚数据类型,对吧?
举个例子,如果我们有:
a b c d
i1 1 1 2 1
i2 2 2 1 1
我想能够这样说:
for f in some_iterator():
print 'a is ' str(f['a'])
print f['b'] + f['c']
#skip f['d']
但是现在,我不能依赖列名,比如 "a,b,c,d" 来做到这一点。
1 个回答
1
假设 df
是一个 pandas.DataFrame 对象。
我们可以通过以下方式来遍历每一行:
for row in df.iterrows():
print str(row[0]) + " is the index of the row"
print str(row[1]) + " is a series with rows having \
labels the same as the columns of the dataframe"