簡體   English   中英

將 function 應用於列表系列,而不應用於 pandas

[英]Apply a function to series of list without apply in pandas

我有一個 dataframe

df = pd.DataFrame({'Binary_List': [[0, 0, 1, 0, 0, 0, 0],
                                   [0, 1, 0, 0, 0, 0, 0],
                                   [0, 0, 1, 1, 0, 0, 0],
                                   [0, 0, 0, 0, 1, 1, 1]]})
df

    Binary_List
0   [0, 0, 1, 0, 0, 0, 0]
1   [0, 1, 0, 0, 0, 0, 0]
2   [0, 0, 1, 1, 0, 0, 0]
3   [0, 0, 0, 0, 1, 1, 1]

我想將 function 應用於每個列表,不使用apply因為在大型數據集上運行時apply非常慢

def count_one(lst):
    index = [i for i, e in enumerate(lst) if e != 0]
    # some more steps 
    return len(index)

df['Value'] = df['Binary_List'].apply(lambda x: count_one(x))
df

    Binary_List             Value
0   [0, 0, 1, 0, 0, 0, 0]   1
1   [0, 1, 0, 0, 0, 0, 0]   1
2   [0, 0, 1, 1, 0, 0, 0]   2
3   [0, 0, 0, 0, 1, 1, 1]   3

我試過用這個,但沒有改善

vfunc = np.vectorize(count_one)
df['Value'] = vfunc(df['Binary_List']) 

這給了我錯誤

df['Value'] = count_one(df['Binary_List'])

要獲取列表項的長度,您可以使用 str function 如下所示

df = pd.DataFrame({'Binary_List': [[0, 0, 1, 0, 0, 0, 0],
                                   [0, 1, 0, 0, 0, 0, 0],
                                   [0, 0, 1, 1, 0, 0, 0],
                                   [0, 0, 0, 0, 1, 1, 1]]})

df["Binary_List"].astype(np.str).str.count("1")

你可以試試DataFrame.explode

df.explode('Binary_List').reset_index().groupby('index').sum()

        Binary_List
index   
0        1
1        1
2        2
3        3

你也可以這樣做:

pd.Series([np.array(key).sum() for key in df['Binary_List']])
0    1
1    1
2    2
3    3
dtype: int64

暫無
暫無

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

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