簡體   English   中英

使用List Comprehension對Pandas數據幀進行迭代

[英]Iteration over a Pandas dataframe using a List Comprehension

我可以用另一種方式解決 但是,我有興趣理解為什么嘗試使用列表推導迭代pandas DataFrame不起作用。 (這里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不再是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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM