首页 > 解决方案 > Pandas 拆分列表列表系列以查找字数/行

问题描述

我有一个过去 24 小时内按 dt.datetime 小时分组的推文数据框,其中每一行是该小时内推文的列表列表我的目标是为每一行拆分和展平这些推文,这样我就可以过滤掉停用词(the、a、but),并获得每小时推文的词频计数。我的实际数据每小时有 2-3k 条推文,因此由于最终目标是以以下格式对数据进行分组,因此我还需要按前 10-15 个最高计数过滤字数。

df =

      hour     tweets
0     1:00     ["['this darn tweet'], ['tweet']"]
1     2:00     ["['another tweet'], ['tweet'], ['tweet']"]
2     3:00     ["['this tweet'], ['this tweet']"]
3     4:00     ["['tweet'], ['this tweet']"]
4     5:00     ["['tweet'], ['another tweet'], ['yet another tweet'], ['tweet']"]

因为这个分组的每小时数据在数据框中而不是列表中,所以我能想到的唯一方法是某种形式的 Series.split() - 这会产生错误:

[in]:
df['tweets'] = [tweet.Series.split() for tweet in df['tweets']]
[out]:
AttributeError: 'list' object has no attribute 'split'

我对这个错误的研究已经深入,我似乎找不到任何拆分一系列列表的例子,但我怀疑这是某种形式的列表理解。

预期结果:

      hour     tweet  this     another   darn   yet
0     1:00     2      1        0         1      0
1     2:00     3      1        1         0      0
2     3:00     2      2        0         0      0
3     4:00     2      1        0         0      0
4     5:00     4      0        2         0      1

标签: pythonpandasdataframetwitter

解决方案


让我们试试:

stopwords = ['the', 'a', 'but']

# extract all the words from list of string
words = df['tweets'].str[0].str.extractall(r'(\w+)')[0]

# Remove stopwords and create frequency table
table = words[~words.isin(stopwords)].str.get_dummies().sum(level=0)

# join with hour column
df[['hour']].join(table)

细节:

tweets首先使用以下方法从列中提取所有单词.str.extractall

   match
0  0           this
   1           darn
   2          tweet
   3          tweet
1  0        another
   1          tweet
   2          tweet
   3          tweet
2  0           this
   1          tweet
   2           this
   3          tweet
3  0          tweet
   1           this
   2          tweet
4  0          tweet
   1        another
   2          tweet
   3            yet
   4        another
   5          tweet
   6          tweet
Name: 0, dtype: object

然后使用布尔掩码stopwords从上面提取的单词中删除,并将单词.str.get_dummies编码为指标/虚拟变量。在对单词进行编码后.sumlevel=0获取每个单词的计数hour

   another  darn  this  tweet  yet
0        0     1     1      2    0
1        1     0     0      3    0
2        0     0     2      2    0
3        0     0     1      2    0
4        2     0     0      4    1

最后.join上面带有列的频率表hour可以得到想要的结果:

   hour  another  darn  this  tweet  yet
0  1:00        0     1     1      2    0
1  2:00        1     0     0      3    0
2  3:00        0     0     2      2    0
3  4:00        0     0     1      2    0
4  5:00        2     0     0      4    1

推荐阅读