【问题标题】:create column flag containing word from list从列表中创建包含单词的列标志
【发布时间】:2018-01-14 01:12:20
【问题描述】:

如果列中的条目包含列表中的单词,我想向我的 python pandas 数据框添加一个标志

对于我们可以使用的任何单独的行

any(word in train['a'][0] for word in words) 

我试着做一个图案

import pandas as pd
import numpy as np
words=['photos','pictures', ' pics ', 'pix', 'image']
pattern = '|'.join(words)

train=pd.DataFrame()
train['a']=words

我尝试过包含但没有得到模式

def emb_col_1(tr, te, col, pat, suf):
    tr["0_"+col+suf]=0
    tr.loc[tr[col].str.contains(pat), "0_"+col+suf] =1
    #tr.loc[tr[col].str.count(pat)>0, "0_"+col+suf] =1
    #tr.loc[(word in tr[col].str for word in pat), "0_"+col+suf] =1
    #tr["0_"+col+suf] = np.where(tr[col].str.contains(pat, case=False, na=False), 1, 0)
    #tr["0_"+col+suf] = np.where(any(word in train[col] for word in pat), 1, 0)


emb_col_1(train, test, 'a', words, '_p')
emb_col_1(train, test, 'a', pattern, '_p')

提前谢谢你

【问题讨论】:

  • 你在函数末尾使用return tr吗?
  • 谢谢,你说得对

标签: python string pandas


【解决方案1】:

我相信你需要:

words=['photos','pictures', ' pics ', 'pix', 'image']
#remeove trailining whitespaces by strip
pattern = '|'.join([x.strip() for x in words])

train=pd.DataFrame()
#added more values for test
train['a']=words + ['a','pics sss']
print (train)

#remove unused te
def emb_col_1(tr, col, pat, suf):
    #convert True and Falses to 1 and 0 by astype(int)
    tr["0_"+col+suf] = tr[col].str.contains(pat, case=False, na=False).astype(int)
    #return DataFrame
    return tr


df1 = emb_col_1(train, 'a', pattern, '_p')
print (df1)
          a  0_a_p
0    photos      1
1  pictures      1
2     pics       1
3       pix      1
4     image      1
5         a      0
6  pics sss      1

编辑:

words=['photos',' pics ', 'pix', 'image']
#remeove trailining whitespaces by strip
pattern = '|'.join([r'\b{}\b'.format(x.strip()) for x in words])

train=pd.DataFrame()
#added more values for test
train['a']=words + ['a','pics sss', 'pictures']
print (train)
          a
0    photos
1     pics 
2       pix
3     image
4         a
5  pics sss
6  pictures

#remove unused te
def emb_col_1(tr, col, pat, suf):
    #convert True and Falses to 1 and 0 by astype(int)
    tr["0_"+col+suf] = tr[col].str.contains(pat, case=False, na=False).astype(int)
    #return DataFrame
    return tr


df1 = emb_col_1(train, 'a', pattern, '_p')
print (df1)
          a  0_a_p
0    photos      1
1     pics       1
2       pix      1
3     image      1
4         a      0
5  pics sss      1
6  pictures      0

【讨论】:

  • 一个注释 - 即使 [words] 中的单词是字符串中单词的一部分(不是单独的单词),也会应用模式 类似模式 'picture' 也将计算 'pictures'跨度>
  • 我觉得应该很好用,有问题吗?
  • 是的,然后需要字边界我认为你需要将pattern = '|'.join([x.strip() for x in words]) 更改为pattern = '|'.join([r'\b{}\b'.format(x) for x in words])。你能检查一下吗?
  • 可能两者结合效果更好pattern = '|'.join([r'\b{}\b'.format(x.strip()) for x in words])
  • 再次感谢您的帮助!
猜你喜欢
  • 2020-02-02
  • 1970-01-01
  • 2013-07-10
  • 1970-01-01
  • 2015-07-26
  • 2021-12-17
  • 1970-01-01
  • 2017-08-20
  • 1970-01-01
相关资源
最近更新 更多