如何在熊猫中进行细胞的阵列操作

时间:2018-09-23 12:55:05

标签: python pandas

基本上,我的数据框如下所示:

id   |   refers 
----------------
1    |   [2,3]
2    |   [1,3]
3    |   []

我想添加另一列,以显示该ID被另一个ID引用了多少次。例如:

id   |   refers  |  referred_count
----------------------------------
1    |   [2,3]   |   1
2    |   [1,3]   |   1
3    |   []      |   2

我当前的代码如下:

citations_dict = {}
for index, row in data_ref.iterrows():
    if len(row['reference_list']) > 0:
        for reference in row['reference_list']:
            if reference not in citations_dict:
                citations_dict[reference] = {}
                d = data_ref.loc[data_ref['id'] == reference]
                citations_dict[reference]['venue'] = d['venue']
                citations_dict[reference]['reference'] = d['reference']
                citations_dict[reference]['citation'] = 1
            else:
                citations_dict[reference]['citation'] += 1

问题在于,这段代码花费了很长时间。我想知道如何更快地执行此操作,也许使用熊猫?

3 个答案:

答案 0 :(得分:1)

第1步:获取引用列中每个ID的计数并将其存储在字典中,然后将该函数应用于创建新列。

import pandas as pd
from collections import Counter

df = pd.DataFrame({'id':[1,2,3],'refers':[[2,3],[1,3],[]]})
counter = dict(Counter([item for sublist in df['refers'] for item in sublist]))
df['refer_counts'] = df['id'].apply(lambda x: counter[x])

输出

   id  refers  refer_counts
0   1  [2, 3]             1
1   2  [1, 3]             1
2   3      []             2

认为这正是您所需要的!

答案 1 :(得分:1)

数据

df = pd.DataFrame({'id': [1,2,3], 'refers': [[1,2,3], [1,3], []]})
    id  refers     referred_count
0   1   [1, 2, 3]   1
1   2   [1, 3]      1
2   3   []          2

创建引用的出现次数字典:

refer_count = df.refers.apply(pd.Series).stack()\
                .reset_index(drop=True)\
                .astype(int)\
                .value_counts()\
                .to_dict()

通过其id_count减去每个ID中的推荐人:

df['referred_count'] = df.apply(lambda x: refer_count[x['id']] - x['refers'].count(x['id']), axis = 1)

输出

    id  refers    referred_count
0   1   [1, 2, 3]  1
1   2   [1, 3]     1
2   3   []         2

答案 2 :(得分:1)

首先使用numpy.hstackSeries.value_counts创建一个助手Series

这将是您的列“ referred_count”的值,其中id为索引。

然后,您可以将df的reset_index转换为id,以便轻松合并本系列,最后使用reset_index将DataFrame恢复为原始形状。

s = pd.Series(np.hstack(df['refers'])).value_counts()
df.set_index('id').assign(referred_count=s).reset_index()

[出]

   id  refers  referred_count
0   1  [2, 3]               1
1   2  [1, 3]               1
2   3      []               2