【问题标题】:String startswith a particular text字符串以特定文本开头
【发布时间】:2017-06-08 14:14:43
【问题描述】:

我正在尝试读取一个 csv 文件,并且我必须根据某些条件进行列操作。 它完全忽略了我的 if 条件并执行 else 语句。 经过大量故障排除后它很痛苦,我无法纠正它。

代码如下:
Tweet 是我的推文列名...

inf = pd.read_csv('string.csv')
for r in inf : 
    if "RT @" in inf.Tweet :   
        inf["Engagements"] = 0  
    else : 
        inf["Engagements"] = inf["Favorite_Count"] + inf["Retweet_Count"]

inf.to_csv('string2.csv', index=False)

【问题讨论】:

  • 为什么你的循环不使用r?顺便说一句,如果这是一个 Pandas 问题,那么你应该给它pandas 标签。
  • @NicholasFlees,没有 inf['Engagements'] 用于访问该特定列...r['Engagements'] 给出错误“字符串索引必须是整数,而不是 str”跨度>

标签: python string pandas if-statement twitter


【解决方案1】:

在处理数组的 pandas 中,因此需要 numpy.where 和由 str.contains 创建的布尔掩码和 ^ 用于 string 的开头或使用 str.startswith

inf["Engagements"] = np.where(inf["Tweet"].str.contains('^RT @'), 
                              0, 
                              inf["Favorite_Count"] + inf["Retweet_Count"])

示例:

inf["Engagements"] = np.where(inf["Tweet"].str.contains('^RT @'), 
                              0, 
                              inf["Favorite_Count"] + inf["Retweet_Count"])

print (inf)
   Favorite_Count  Retweet_Count     Tweet  Engagements
0               1              2  RT @ ddd            0
1               4              0        dd            4
2               5              7  dds RT @           12

inf["Engagements"] = np.where(inf["Tweet"].str.startswith('RT @'), 
                              0, 
                              inf["Favorite_Count"] + inf["Retweet_Count"])

print (inf)
   Favorite_Count  Retweet_Count     Tweet  Engagements
0               1              2  RT @ ddd            0
1               4              0        dd            4
2               5              7  dds RT @           12

【讨论】:

    【解决方案2】:

    您可以先将Engagement 列初始化为零。然后创建一个掩码来查找不以“RT @”开头的推文(注意~ 否定)。最后,使用掩码添加Favorite_CountRetweet_Count 列。

    请注意,您很少希望对数据框使用循环。

    inf = pd.read_csv('string.csv')
    
    inf['Engagement'] = 0
    mask = ~inf.Tweet.str.startswith('RT @')
    inf.loc[mask, 'Engagement'] = (
        inf.loc[mask, 'Favorite_Count'] 
        + inf.loc[mask, 'Retweet_Count']
    )
    

    例子:

    # Sample data.
    inf = pd.DataFrame(
        {'Tweet': ["RT @ something", "something that doesn't start with RT @", "something else"],
         'Favorite_Count': [1, 2, 3], 
         'Retweet_Count': [3, 2, 1]})
    
    # Apply code
    inf['Engagement'] = 0
    mask = ~inf.Tweet.str.startswith('RT @')
    inf.loc[mask, 'Engagement'] = (
        inf.loc[mask, 'Favorite_Count'] 
        + inf.loc[mask, 'Retweet_Count']
    )
    
    >>> inf[['Favorite_Count', 'Retweet_Count', 'Engagement', 'Tweet']]
        Favorite_Count  Retweet_Count   Engagement  Tweet
    0   1   3   0   RT @ something
    1   2   2   4   something that doesn't start with RT @
    2   3   1   4   something else
    

    【讨论】:

      【解决方案3】:

      除了上面简洁的回答,如果你想使用类似的if else结构,你可以使用set_value来设置特定行和列的值。

      import pandas as pd
      inf = pd.read_csv('string.csv')
      for index,row in inf.iterrows():
          if "RT @" in row["Tweet"]:
              inf.set_value(index, "Engagements", 0)
          else:
              inf.set_value(index, "Engagements", row["Favorite_Count"] + row["Retweet_Count"])
      inf.to_csv('string2.csv', index=False)
      

      【讨论】:

      • 谢谢朋友,我完全忘记了 iterrows() 方法。它的工作。非常感谢。
      【解决方案4】:

      if string.startswith(whateveritshouldstartwith):

      这是正确的做法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-08
        • 2012-12-04
        • 2011-06-16
        • 2017-09-20
        • 2023-03-16
        • 1970-01-01
        • 2020-05-11
        • 1970-01-01
        相关资源
        最近更新 更多