【发布时间】:2020-07-04 12:07:26
【问题描述】:
我有以下两个数据框badges 和comments。我从 badges 数据框创建了一个“黄金用户”列表,其 Class=1。
这里Name 表示“徽章名称”,Class 表示徽章等级(1=金,2=银,3=铜)。
我已经对comments['Text']进行了文本预处理,现在想从comments['Text']中查找金牌用户的前10个字数。
我尝试了给定的代码,但出现错误
"KeyError: "没有 [Index(['1532', '290', '1946', '1459', '6094', '766', '10446', '3106', '1',\n '1587 ',\n ...\n '35760', '45979', '113061', '35306', '104330', '40739', '4181', '58888',\n '2833', '58158' ],\n dtype='object', length=1708)] 在 [index]" 中。请提供解决此问题的方法。
注意 我从 datascience.stackexchange 得到了一些答案,但没有奏效。 Link to StackExchange Problem
数据框 1(徽章)
Id | UserId | Name | Date |Class | TagBased
2 | 23 | Autobiographer | 2016-01-12T18:44:49.267 | 3 | False
3 | 22 | Autobiographer | 2016-01-12T18:44:49.267 | 3 | False
4 | 21 | Autobiographer | 2016-01-12T18:44:49.267 | 3 | False
5 | 20 | Autobiographer | 2016-01-12T18:44:49.267 | 3 | False
6 | 19 | Autobiographer | 2016-01-12T18:44:49.267 | 3 | False
数据框 2 (cmets)
Id| Text | UserId
6| [2006, course, allen, knutsons, 2001, course, ... | 3
8| [also, theo, johnsonfreyd, note, mark, haimans... | 1
代码
#Classifying Users
df_gold_users = badges[(badges['Class'] == '1')]
df_silver_users = badges[(badges['Class'] != '1') & (badges['Class'] == '2') ]
df_bronze_users = badges[(badges['Class'] != '1') & (badges['Class'] != '2') & (badges['Class'] == '3')]
gold_users = df_gold_users['UserId'].value_counts().index
silver_users = df_silver_users['UserId'].value_counts().index
bronze_users = df_bronze_users['UserId'].value_counts().index
#Text Cleaning (clean_text function tokenizes and lemmatizes)
comments['Text'] = comments['Text'].apply(lambda x: clean_text(x))
#Getting comments made by Gold Users
for index,rows in comments.iterrows():
gold_comments = rows[comments.Text.loc[gold_users]]
Counter(gold_comments)
预期输出
#Top 10 Words that appear the most in the comments made by gold users with their count.
[['scholar',20],['school',18],['bus',15],['class',14],['teacher',14],['bell',13],['time',12],['books',11],['bag',9],'student',7]]
【问题讨论】:
-
也许您可以发布一个更完整的代码示例,例如
gold_users的结构会很重要。您可以尝试用comments.UserId.isin(gold_users)替换gold_users吗?假设您想通过UserId而不是数据框索引查找... -
badges[badges['id'].isin(comments['id'].tolist())]?不确定您需要/想要什么,请发布您的预期输出 -
@DavidWierichs 我已经添加了完整的代码,请看一下。
-
@Datanovice 我已经添加了预期的输出。简而言之,我从
badges数据框中找到了class=1的用户,即黄金。现在我想为那些黄金用户分离comments['Text']行,以便最终找出黄金用户使用的前 10 个单词。 -
@DavidWierichs 我试过你的方法,它给出了错误:
TypeError: unhashable type: 'list'
标签: python-3.x pandas dataframe nlp pandas-groupby