【问题标题】:How to count the number of list elements embedded in a datafrane column?如何计算数据框列中嵌入的列表元素的数量?
【发布时间】:2022-11-28 06:27:41
【问题描述】:

我有一个如下所示的数据框(包括括号和引号):

ID Interests
2131 ['music','art','travel']
3213 []
3132 ['martial arts']
3232 ['martial arts']

我试图获得的期望输出是:

ID Interests
2131 3
3213 0
3132 1
3232 1

我试过使用

from collections import Counter
ravel = np.ravel(user.personal_interests.to_list())

但这只是给了我每个组合的数量,即: ['武术']:2

我也试过去掉引号并使用一个系列来计算,但无济于事。

【问题讨论】:

    标签: python pandas list dataframe numpy


    【解决方案1】:

    您可以尝试使用长度()Python 中的方法

    如果去向是你的数据框,

    temp = []
    
    df['Interests'].apply(lambda x: temp.append(len(x)))
    
    df['new_interests'] = temp
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2021-12-27
      • 2019-03-04
      • 2010-10-10
      • 1970-01-01
      • 2018-07-25
      相关资源
      最近更新 更多