【发布时间】:2018-09-22 18:53:41
【问题描述】:
我有一个包含几列的数据框,如下所示:
id | x1 | text | x2 | num | x3 | class
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT |
2nn| TT | word | QQ | 1 | TT | # They don't all have the same vals
2nn| TT | word | QQ | 1 | TT | # This is just to illustrate it
我还有以下带有字符串的lists:
class1 = ["",...]
class2 = ["",...]
class3 = ["",...]
class4 = ["",...]
class5 = ["",...] # Multiple strings, I just used '...' for simplicity
我正在尝试在class 列中分配类,这样如果事务(行)的text 列中的单词包含在任何lists 中找到的任何单词,则将列表名称指定为类.
我这样做是为了标记一些我最终将用于分类的数据。
我只想对从第 10,000 行开始的数据执行此标记。我使用的是:
# last 6000 rows
for index, row in df.tail(6000).iterrows():
if df[df['text'].str.contains(class1)==True]:
df.loc[row, 'class'] = "class1"
if df[df['text'].str.contains(class2)==True]:
df.loc[row, 'class'] = "class2"
if df[df['text'].str.contains(class3)==True]:
df.loc[row, 'class'] = "class3"
if df[df['text'].str.contains(class4)==True]:
df.loc[row, 'class'] = "class4"
if df[df['text'].str.contains(class5)==True]:
df.loc[row, 'class'] = "class5"
我收到一个打印以下错误的响应:
TypeError: unhashable type: 'list'
以下是我在尝试 Chris A 的回复时的代码:
# Word bins for the various labels
complaint = ["sucks", "worst", "doesn't", "didn't", "won't", "bad", "horrible", "unusable", "cannot", "can't", "not", "did not", "waste", "hate", "hated", "awful", "useless", "sucked", "freezing", "freezes", "froze", "does not", "crap", "stupid"]
compliment = ["awesome", "great", "amazing", "cool", "good", "nice", "nicest", "successful", "thanks", ":)", "successfully"]
neutral = ["Eh", "meh", "works"]
bug = ["please", "fix", "won't", "cannot", "can't", "not", "freezing", "freezes", "froze", "does not", "did not", "help", "plz"]
feature = ["it would be", "id like", "i'd like", "could", "can you", "implement", "feature", "lacks", "wish"]
def label_data(df):
d = {'Compliment': compliment,
'Complaint': complaint,
'Neutral': neutral,
'Bug': bug,
'Feature': feature}
for name, values in d.items():
df.loc[df['review'].isin(values), 'label'] = name
我的主类调用文本文件中的数据,然后使用以下方法调用此方法:
df_orig = pd.read_table("PRIVATEPATH/data.txt", delimiter=",")
label_data(df_labelled)
【问题讨论】:
标签: python pandas dataframe anaconda