繁体   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