使用列表理解对Pandas数据帧进行迭代

2024-09-29 21:28:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以用另一种方法来解决这个问题;但是,我有兴趣确切地理解为什么用列表理解来迭代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."

Tags: ofthe数据indataframeforindexif
1条回答
网友
1楼 · 发布于 2024-09-29 21:28:58

问题是在第一行之后,a不再是数据帧:

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]]

它是一个列表,因此没有index属性(因此出现错误)。在

python的一个诀窍是在一行中完成此操作(同时定义它们),即:

^{pr2}$

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

就像你说的,在大熊猫身上有更好的方法,最明显的就是使用面具:

msk = sorted1 < sorted2

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

相关问题 更多 >

    热门问题