python – 使用List Comprehension迭代Pandas数据帧

我可以用另一种方式解决但是,我有兴趣理解为什么尝试使用列表推导迭代pandas DataFrame不起作用. (这里是一个数据帧)

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不再是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]]

它是一个列表,因此没有索引属性(因此错误).

一个python技巧是在一行中执行此操作(同时定义它们),即:

a, b = [a.ix[i] for ...], [a.ix[i] for ...]

也许更好的选择是在这里使用不同的变量名称(例如df).

就像你说的,有更好的方法在熊猫中做到这一点,显而易见的是使用一个面具:

msk = sorted1 < sorted2

seed1 = df[msk].mean()
seed2 = df[~msk].mean()

相关文章

转载:一文讲述Pandas库的数据读取、数据获取、数据拼接、数...
Pandas是一个开源的第三方Python库,从Numpy和Matplotlib的基...
整体流程登录天池在线编程环境导入pandas和xrld操作EXCEL文件...
 一、numpy小结             二、pandas2.1为...
1、时间偏移DateOffset对象DateOffset类似于时间差Timedelta...
1、pandas内置样式空值高亮highlight_null最大最小值高亮背景...