【问题标题】:Apply a function to series of list without apply in pandas将函数应用于一系列列表而不在熊猫中应用
【发布时间】:2019-09-28 00:04:15
【问题描述】:

我有一个数据框

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]

我想对每个列表应用一个函数,而不使用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'])

【问题讨论】:

  • 你不能,因为你在 DataFrame 中存储了一个 object。如果您只是将每个元素存储为自己的单元格,那么这是一个微不足道且非常快速的df.sum(1)
  • 假设它是针对您之前的问题 - stackoverflow.com/q/58136267。使用已发布答案的中间输出,其中您有二进制数组输出并沿 cols 求和 - .sum(axis=1)
  • 猜你需要堆叠和求和:np.vstack(df['Binary_Month_List']).sum(1).
  • 正如我在之前的问答中所说的,没有神奇的功能。
  • 据我所知,downvotes(和 up)是匿名的。我怀疑大多数投反对票的人不会留下来跟随 cmets。

标签: python pandas numpy


【解决方案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

【讨论】:

    【解决方案2】:

    为了获取列表项的长度,您可以使用 str 函数,如下所示

    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")
    

    【讨论】:

      猜你喜欢
      • 2020-05-12
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多