【问题标题】:assigning a value to specific words in a dataframe in python在python中为数据框中的特定单词赋值
【发布时间】:2020-08-22 14:50:16
【问题描述】:

您好,我有一个由 7989 行 × 1 列组成的数据框。 不同的行是不同海上海盗袭击的后果。

然后,我想根据特定单词是否包含在下面的不同列表之一中,为不同的行分配一个值。然后分配的值将取决于不同的列表。

6 个列表:

five =['kill','execute','dead']
four =['kidnap','hostag','taken','abduct']
three =['injur','wound','assault']
two =['captur','hijack']
one =['stolen','damage','threaten','robber','destroy']
zero =['alarm','no','none']

我尝试过这样做:

df['five']=df.apply(lambda x: '5' if x == 'five' else '-')

df 是我的数据框

谁能帮忙?

【问题讨论】:

  • 你能在你的问题中嵌入一个简短的例子吗?

标签: python pandas list dataframe nlp


【解决方案1】:

您可以为每个列表创建带有数字值merge all dictionaries together 的字典,然后通过numpy.where 设置新列:

df = pd.DataFrame({'outcom':[['kill','dead'],['abduct','aaaa'],['hostag']]})

#same way add another lists
five = ['kill','execute','dead']
four = ['kidnap','hostag','taken','abduct']   
three =['injur','wound','assault']
two =['captur','hijack']
one =['stolen','damage','threaten','robber','destroy']
zero =['alarm','no','none']    

#same way add another dicts
d5 = dict.fromkeys(five, '5')
d4 = dict.fromkeys(four, '4')
d3 = dict.fromkeys(three, '3')
d2 = dict.fromkeys(two, '2')
d1 = dict.fromkeys(one, '1')
d0 = dict.fromkeys(zero, '0')

d = {**d5, **d4, **d3, **d2, **d1, **d0}
print (d)

for k, v in d.items():
    df[k] = np.where(df['outcom'].apply(lambda x: k in x), v, '-')

print (df)
           outcom kill execute dead kidnap hostag taken abduct
0    [kill, dead]    5       -    5      -      -     -      -
1  [abduct, aaaa]    -       -    -      -      -     -      4
2        [hostag]    -       -    -      -      4     -      -

【讨论】:

    【解决方案2】:

    编辑

    您可以像这样使用loc 函数(documentation):

    将熊猫导入为 pd

    five = ["I", "like"]
    df = pd.DataFrame(["I", "like", "bacon", "in", "the", "morning"], columns=["Words"])
         Words
    0        I
    1    likes
    2    bacon
    3       in
    4      the
    5  morning
    
    df["New"] = df["Words"].copy()
    df.loc[df["New"] == "I", "New"] = 5
    
         Words      New
    0        I        5
    1     like     like
    2    bacon    bacon
    3       in       in
    4      the      the
    5  morning  morning
    

    然后您可以使用 for 循环来帮助您

    【讨论】:

    • 非常感谢!但是我会创建一个新列,其中我的值是 0-5,具体取决于是否包含该单词。而且不能说 df['new_name_column'] = df.where(df ==['kidnap','hostag','taken','abduct], 4)
    • 我想我也可以做一个循环,但它不起作用。 ://
    • 那可能是因为我犯了一个错误,不像numpy pandas的@​​987654324@替换了DONT持有条件的值
    • @SofieAmalieBodenhoff 我修正了我的答案并运行了代码,它可以工作:)
    • 我试过了,还是不行。我有一列有多个单词是这个问题吗?
    【解决方案3】:

    感谢大家的帮助,我想我找到了让它工作的方法:

     list_of_words = zero + one + two + three + four + five
    
         outcome_refined = df_Stop2['outcome'].apply(lambda x: [item for item in x if item 
          in list_of_words])
    
    
    
     outcome_numbered=[] #Create an empty list
    
    def max_val(list): #Ensures that then we only get the largest possible value
    
    maximum_value = 0
    
    for i in list:
       
       if i > maximum_value:
    
            maximum_value = i
    
    return [maximum_value]
    
            
     #Make sure that you loop through each of the lists
        
     for words in outcome_refined:
        tmp = [] #Create a temprorary empty list
        for word in words:
          if word in zero:
              word = 0
          elif word in one:
              word = 1
          elif word in two:
              word = 2
          elif word in three:
              word = 3
          elif word in four:
              word = 4
          elif word in five:
              word = 5   
          tmp.append(word)
        tmp = max_val(tmp)
        outcome_numbered.append(tmp)
    
    
    df_Stop['outcome_numbered']=outcome_numbered.copy()   
    
    df_Stop
    

    Finally working

    【讨论】:

      猜你喜欢
      • 2018-10-27
      • 2021-09-14
      • 2021-02-10
      • 1970-01-01
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      相关资源
      最近更新 更多