[英]Count values in a dataframe column of lists
我在 dataframe 中有一個看起來像這樣的列
0 NaN
1 ["arts"]
2 ["sports", "tech"]
3 ["arts", "finance", "health", "sports", "science"...
4 ["finance", "sports", "tech"]
5 ["arts", "finance", "sports", "tech"]
6 ["arts", "finance", "health", "sports", "science"...
7 ["arts", "sports", "science"]
我很想知道藝術在所有這些列表中出現了多少次。 但是,在嘗試column.explode().value_counts(sort=True)
時,我只是得到了一個帶有選項的基本分布,這不是我想要的。
["tech"] 5
["arts", "finance", "sports", "tech"] 2
["arts", "sports"] 2
["finance", "sports"] 1
["arts"] 1
我什至嘗試使用計數器collections.Counter(itertools.chain.from_iterable(v.split(',') for v in column))
但我收到以下錯誤'float' object has no attribute 'split'
任何指針?
如果column
不是太長,一個簡單的嵌套循環應該可以正常工作:
count = 0
for str_list in column:
for name in str_list:
if name == "arts":
count += 1
print(count)
您可以通過執行以下操作來創建包含藝術的行掩碼:
mask = df['industry'].apply(lambda x: 'comedy' in x)
然后將您的 dataframe 限制為您的新面罩
df = df[mask]
從那里你應該能夠使用 len(df) 或類似的東西。
如果您正在尋找的行業可以在每一行中出現不止一次,您可以使用您的 itertools 想法。 浮動錯誤來自嘗試拆分 NaN,因此請確保在嘗試連接列表之前使用 dropna()。
list(itertools.chain.from_iterable(df['industry'].dropna().values)).count('arts')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.