我可以用另一种方法来解决这个问题;但是,我有兴趣确切地理解为什么用列表理解来迭代pandas数据帧是行不通的。(这里a
是一个数据帧)
def func(a,seed1,seed2):
for i in range(0,3):
# Sum of squares. Results in a series containing 'date' and 'num'
sorted1 = ((a-seed1)**2).sum(1)
sorted2 = ((a-seed2)**2).sum(1)
# This makes a list out of the dataframe.
a = [a.ix[i] for i in a.index if sorted1[i]<sorted2[i]]
b = [a.ix[i] for i in a.index if sorted1[i]>=sorted2[i]]
# The above line throws the exception:
# TypeError: 'builtin_function_or_method' object is not iterable
# Throw it back into a dataframe...
a = pd.DataFrame(a,columns=['A','B','C'])
b = pd.DataFrame(b,columns=['A','B','C'])
# Update the seed.
seed1 = a.mean()
seed2 = b.mean()
print a.head()
print "I'm computing."
问题是在第一行之后,a不再是数据帧:
它是一个列表,因此没有index属性(因此出现错误)。在
python的一个诀窍是在一行中完成此操作(同时定义它们),即:
^{pr2}$也许更好的选择是在这里使用不同的变量名(例如df)。在
就像你说的,在大熊猫身上有更好的方法,最明显的就是使用面具:
相关问题 更多 >
编程相关推荐