获取多于1个的字数索引值

时间:2018-06-25 12:24:18

标签: python pandas dataframe pandas-groupby

我正在尝试获取索引值以及列表中每个单词的计数均大于1。

Ref="easy to get to know to easy of to"

使用Ref输入,此表为df1

 word   Count
 easy   2
  to    4
 get    1
 know   1
  of    1

df

Index   word
   0    easy
   1    to
   2    get
   3    to
   4    know
   5    to
   6    easy
   7    of
   8    to

所以从这两个表dfdf1中我想要的是

Index          word   count
[0,6]          easy     2
[1,3,5,8]       to      4
[2]             get     1
[4]            know     1
[7]             of      1

如果有人帮助我,这真的很棒。

2 个答案:

答案 0 :(得分:2)

将df设为

       word
Index      
0      easy
1        to
2       get
3        to
4      know
5        to
6      easy
7        of
8        to

首先,使用reset_index将数据框索引移到名为“索引”的列中:

df = df.reset_index()

接下来使用以下groupbyagg

df.groupby('word')['Index'].agg([list,'count']).reset_index()

输出:

   word          list  count
0  easy        [0, 6]      2
1   get           [2]      1
2  know           [4]      1
3    of           [7]      1
4    to  [1, 3, 5, 8]      4

答案 1 :(得分:1)

groupby +地图

您可以在word中按df分组,然后在word中按df1映射:

s = df.groupby('word')['Index'].apply(list)
df1['Index'] = df1['word'].map(s)

print(df1)

   word  Count         Index
0  easy      2        [0, 6]
1    to      4  [1, 3, 5, 8]
2   get      1           [2]
3  know      1           [4]
4    of      1           [7]

defaultdict

或者,从第一原理开始,您可以使用collections.defaultdict来构造包含索引的列表的字典。然后输入pd.DataFrame

from collections import defaultdict

Ref = "easy to get to know to easy of to"

d = defaultdict(list)

for idx, word in enumerate(Ref.split()):
    d[word].append(idx)

df = pd.DataFrame({'word': list(d.keys()), 'Index': list(d.values())})
df['count'] = df['Index'].map(len)

print(df)

          Index  word  count
0        [0, 6]  easy      2
1  [1, 3, 5, 8]    to      4
2           [2]   get      1
3           [4]  know      1
4           [7]    of      1