![](/img/trans.png)
[英]How to efficiently count the number of smaller elements for every element in another column?
[英]How to efficiently count the number of children for each element in a column?
我有一個 dataframe df
如下。
parent_id name
0 t3_35jfjt t1_cr4y72v
1 t3_35jfjt t1_cr4y7m7
2 t3_35jfjt t1_cr4y7p3
3 t1_cr4y72v t1_cr4y92z
4 t3_35jfjt t1_cr4y986
... ... ...
其中列name
中的所有元素都是唯一的。 我想創建一個字典,其鍵是列name
中的元素。 對於每個這樣的鍵,我們在parent_id
列上計算它的頻率。 如果它沒有出現在parent_id
列中,那么這個鍵的值當然是 0。
我這樣做如下,但它效率不高,因為我有超過 300 萬行。 您能否詳細說明一種更有效的方法?
import pandas as pd
import numpy as np
df = pd.read_csv('https://raw.githubusercontent.com/leanhdung1994/WebMining/main/df.csv', header = 0)
# Create df2 to contain the counts
df2 = df.groupby(by = 'parent_id', as_index = False).size()
# Join df2 and df based on column "parent_id"
df3 = pd.merge(df, df2, how = 'left', left_on= 'name', right_on= 'parent_id')
# Replace NaN with 0
df4 = df3.fillna(0).rename(columns = {'size': 'num_siblings'})
df5 = df4[['name', 'num_siblings']]
# My expected dictionary
df5.set_index('name').T.to_dict('records')[0]
這是
{'t1_cr4y72v': 27.0,
't1_cr4y7m7': 26.0,
't1_cr4y7p3': 148.0,
't1_cr4y92z': 0.0,
't1_cr4y986': 43.0,
't1_cr4ya0g': 11.0,
't1_cr4yai8': 1.0,
....
你想要這樣的東西:
import pandas as pd
import numpy as np
df = pd.read_csv('https://raw.githubusercontent.com/leanhdung1994/WebMining/main/df.csv', header = 0)
# Create df2 to contain the counts
df2 = df.groupby(by = 'parent_id').size()
df2.reindex(df['name'], fill_value=0).to_dict()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.