[英]Count number of elements in a list inside a DataFrame's column
我有一個DataFrame
,格式如下:
ID | ID_鏈接 |
---|---|
0 | [10] |
1個 | [11, 12, 13] |
2個 | [14, 15] |
3個 | [16] |
4個 | [17, 18, 19, 20] |
如何知道有多少 ID 具有包含多個元素的 ID_links? 換句話說,該列表中 ID_links 包含超過 1 個值的 ID 的百分比是多少?
偽代碼:
如何在 Python/Spark 中實現它?
比遍歷 DataFrame 的所有行更好的是使用numpy.where
像這樣
import numpy as np
import pandas as pd
df = pd.DataFrame({'ID': {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},
'ID_links': {0: [10], 1: [11, 12, 13], 2: [14, 15], 3: [16], 4: [17, 18, 19, 20]}})
np.where(df.ID_links.map(len) > 1)
output:
(array([1, 2, 4]),)
您可以將該列表中的元素數除以 DataFrame 中的行數以獲得所需的 output
where = np.where(df.ID_links.map(len) > 1)
len(where[0]) / len(df.index) # 0.6 = 60%
如果您有任何問題,請告訴我:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.