python - 基于两列标记数据

标签 python pandas dataframe anaconda

我有一个包含几列的数据框,如下所示:

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 字典 可能会有所帮助。

使用 str.contains 时,您还必须通过使用 |(正则表达式“OR”运算符)连接每个值来“构建”正则表达式字符串。

注意

正如您所发现的,这里的一个问题是,以这种方式构建正则表达式模式将要求您转义列表中的任何特殊正则表达式字符。示例 - 您的赞美列表中有“:)”。这需要变成 '\:\)'

d = {'class1': class1,
     'class2': class2,
     'class3': class3,
     'class4': class4}

for name, values in d.items():
    # Create a regex string joining all the values in the list with the regex OR '|'
    pat = '|'.join(values)
    df.loc[df['text'].str.contains(pat), 'class'] = name

简化示例

df = pd.DataFrame({'id': {0: '2nn',1: '2nn',2: '2nn',3: '2nn',4: '2nn',5: '2nn',6: '2nn',7: '2nn',8: '2nn',9: '2nn',10: '2nn',11: '2nn',12: '2nn'},
                    'x1': {0: 'TT',1: 'TT',2: 'TT',3: 'TT',4: 'TT',5: 'TT',6: 'TT',7: 'TT',8: 'TT',9: 'TT',10: 'TT',11: 'TT',12: 'TT'},
                    'text': {0: 'abc',1: 'abc',2: 'e',3: 'h',4: 'm',5: 'p',6: 'q',7: 'd',8: 's',9: 'j',10: 'h',11: 'o',12: 'z'},
                    'x2': {0: 'QQ',1: 'QQ',2: 'QQ',3: 'QQ',4: 'QQ',5: 'QQ',6: 'QQ',7: 'QQ',8: 'QQ',9: 'QQ',10: 'QQ',11: 'QQ',12: 'QQ'},
                    'num': {0: 1,1: 1,2: 1,3: 1,4: 1,5: 1,6: 1,7: 1,8: 1,9: 1,10: 1,11: 1,12: 1},
                    'x3': {0: 'TT',1: 'TT',2: 'TT',3: 'TT',4: 'TT',5: 'TT',6: 'TT',7: 'TT',8: 'TT',9: 'TT',10: 'TT',11: 'TT',12: 'TT'},
                    'class': {0: np.nan,1: np.nan,2: np.nan,3: np.nan,4: np.nan,5: np.nan,6: np.nan,7: np.nan,8: np.nan,9: np.nan,10: np.nan,11: np.nan,12: np.nan}})

class1 = list('abcde')
class2 = list('fghi')
class3 = list('jklmn')
class4 = list('opqrs')

d = {'class1': class1,
     'class2': class2,
     'class3': class3,
     'class4': class4}

for name, values in d.items():
    pat = '|'.join(values)
    df.loc[df['text'].str.contains(pat), 'class'] = name

print(df)

[输出]

     id  x1 text  x2  num  x3   class
0   2nn  TT    a  QQ    1  TT  class1
1   2nn  TT    b  QQ    1  TT  class1
2   2nn  TT    e  QQ    1  TT  class1
3   2nn  TT    h  QQ    1  TT  class2
4   2nn  TT    m  QQ    1  TT  class3
5   2nn  TT    p  QQ    1  TT  class4
6   2nn  TT    q  QQ    1  TT  class4
7   2nn  TT    d  QQ    1  TT  class1
8   2nn  TT    s  QQ    1  TT  class4
9   2nn  TT    j  QQ    1  TT  class3
10  2nn  TT    h  QQ    1  TT  class2
11  2nn  TT    o  QQ    1  TT  class4
12  2nn  TT    z  QQ    1  TT     NaN

关于python - 基于两列标记数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52459850/

相关文章:

Python Web Scraper : My script is just printing the first one, 而不是全部?

R:对一列中与同一数据框中不同列中的特定值相对应的值进行排序/选择的有效方法

apache-spark - 如何遍历pyspark中的每一行dataFrame

python - 根据某些列中的空值删除行( Pandas )

python - 如何设置 django 在单元测试期间不使用内存数据库?

python - 使用 pathlib 创建符号链接(symbolic link)

python - 比较因子变量每个级别的数据帧的两个连续行的值 - Python Pandas

python - Tfidftransformer 和 Tfidfvectorizer 有什么区别?

python - 使用 re(正则表达式)仅解析一行

python - 将日志记录添加到 jenkins 中的测试结果中