【问题标题】:Pandas Split Series of List of Lists to Find Word Count/RowPandas 拆分列表列表系列以查找字数/行
【发布时间】:2021-02-14 14:04:55
【问题描述】:

我有一个过去 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

【问题讨论】:

  • typedf['tweets'][0] 是什么?
  • df['tweets'] 将是 dtype: object
  • 我需要知道type(df['tweets'][0])的输出?
  • 啊我的错:

标签: python pandas dataframe twitter


【解决方案1】:

让我们试试吧:

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)

详情:

首先使用.str.extractalltweets列中提取所有单词:

   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将单词编码为指标/虚拟变量。对单词进行编码后,在 level=0 上使用 .sum 以获取每个 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

【讨论】:

  • 这成功了!谢谢你。我意识到,由于table 的索引已经是我的时间,我不需要执行连接,只需将索引重置为table['hourindex'] = table.index
  • @GeordiAlm 很高兴我能帮上忙。编码愉快!
  • 对于其他可能遇到此问题的人,您知道如何按最大值对结果(列)进行排序吗? df.ix[:, df.max().sort_values(ascending=False).index] 导致时间戳和 int 类型错误。
  • @GeordiAlm 让我们讨论here
  • hour列设置为index后,可以使用df.iloc[:, np.argsort(df.max() * -1)]df.loc[:, df.max().sort_values(ascending=False).index]
【解决方案2】:

这不是完整的解决方案,而且很详细(这意味着它可以稍微清理一下,但是您会遍历一系列具有列表列表的行,所以我一步一步来看看发生了什么.

可能有正则表达式首先删除所有标点符号和括号,然后循环更容易。因此,如果有人了解系列中的正则表达式,那将很有帮助。

您可以对列表进行字数统计,然后通过将列表发送到 set() 并创建一个新列表来查找唯一性。

tweets = ["['this darn tweet'], ['tweet']"]
print(type(tweets)
list_of_words = []
for tweet in tweets:
    print(tweet)
    print(type(tweet))
    print(tweet.replace('\'','').replace('[','').replace(']','').replace(',',''))
    tweet_stripped = tweet.replace('\'','').replace('[','').replace(']','').replace(',','')
    print(tweet_stripped.split())
    for word in tweet_stripped.split():
        print(word)
        list_of_words.append(word)
print(list_of_words)

这是输出字符串。你可以看到你是如何从一个列表开始的,所以你需要像处理一个列表一样处理它,然后你每个操作一个字符串,收集单词

<class 'list'>
['this darn tweet'], ['tweet']
<class 'str'>
this darn tweet tweet
['this', 'darn', 'tweet', 'tweet']
this
darn
tweet
tweet
['this', 'darn', 'tweet', 'tweet']

要遍历系列,您需要将以上所有内容包装在系列循环中 像

for r in df['tweets']:
    #insert above routine here

【讨论】:

    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2023-01-11
    • 2018-04-07
    • 2021-10-04
    • 1970-01-01
    • 2016-05-31
    相关资源
    最近更新 更多