【问题标题】:Add column to txt with conditional values使用条件值将列添加到 txt
【发布时间】:2017-10-24 19:36:28
【问题描述】:

我有一个 txt_file,其中包含如下行: "2017-03-21 12:00:00","844334879861069999","RT @______: Ein wenig Zelda in der Schule spielen :) #SwitchMoment @NintendoDE URL"

我想在左侧添加一列,其值为 4 表示正数,0 表示负数,具体取决于该行包含正数 (":)",":D") 还是负数笑脸 (":-( ",":(")。如果两种类型都在一条线上,则需要变成 99。我很高兴听到有关如何实现这些结果的任何建议。 我的尝试:

    import pandas as pd
    p_smilies=[":)",":D"]
    n_smilies=[":-(",":("]
    csv_input = pd.read_csv('input.csv')
    csv_input['sentiment']=0
    for line in csv_input["tweets"]:
            for p in p_smilies:
                    if p in line:
                            <ascribe value 4 to corresponding line in csv_input['sentiment]>
            for n in p_smilies:
                    if n in line:
                            <ascribe value 4 to corresponding line in csv_input['sentiment]>
<check whether both are in the same line and ascribe 99 to line>


    csv_input.to_csv('output.csv', index=False)

【问题讨论】:

    标签: python python-3.x pandas twitter


    【解决方案1】:

    您可以将numpy.wherestr.contains 一起使用:

    csv_input = pd.DataFrame({'tweets': ['RT @_______len :) #SwitchMoment ', ':D :-( @NintendoDE URL', ':(', 'Ein wenig Zelda']})
    print (csv_input)
                                 tweets
    0  RT @_______len :) #SwitchMoment 
    1            :D :-( @NintendoDE URL
    2                                :(
    3                   Ein wenig Zelda
    

    我为不笑添加新值3

    p_smilies=[r":\)",r":D"]
    n_smilies=[r":-\(",r":\("]
    
    mp = csv_input["tweets"].str.contains('|'.join(p_smilies))
    mn = csv_input["tweets"].str.contains('|'.join(n_smilies))
    
    csv_input['sentiment'] = np.where(mn & mp, 99, 
                             np.where(mn, 0, 
                             np.where(mp, 4, 3)))
    print (csv_input)
                                 tweets  sentiment
    0  RT @_______len :) #SwitchMoment           4
    1            :D :-( @NintendoDE URL         99
    2                                :(          0
    3                   Ein wenig Zelda          3
    

    或者如果相同的值0 表示否定且没有微笑:

    csv_input['sentiment'] = np.where(mn & mp, 99, 
                             np.where(mp, 4, 0))
    print (csv_input)
                                 tweets  sentiment
    0  RT @_______len :) #SwitchMoment           4
    1            :D :-( @NintendoDE URL         99
    2                                :(          0
    3                   Ein wenig Zelda          0
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-15
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      • 2018-07-19
      相关资源
      最近更新 更多