【问题标题】:DataFrame add boolean column by checking multiple parametersDataFrame通过检查多个参数添加布尔列
【发布时间】:2016-04-15 08:23:46
【问题描述】:

我正在寻找这样的东西。

tweets = pd.DataFrame()

tweets['worldwide'] = [tweets['user.location'] == ["Worldwide", "worldwide", "WorldWide]]

通过检查列 tweets['user.location'],新列 'worldwide' 具有布尔值(True、False),该列具有全球三种不同类型的拼写。

我希望为所有拼写“worldwide”的树格式返回值“True”。

【问题讨论】:

    标签: pandas dataframe boolean ipython


    【解决方案1】:

    IIUC 那么你想要isin:

    tweets['worldwide'] = [tweets['user.location'].isin(["Worldwide", "worldwide", "WorldWide"])]
    

    如果存在任何值,这将返回 True

    In [229]:
    df = pd.DataFrame({'Tweets':['worldwide', 'asdas', 'Worldwide', 'WorldWide']})
    df
    
    Out[229]:
          Tweets
    0  worldwide
    1      asdas
    2  Worldwide
    3  WorldWide
    
    In [230]:
    df['Worldwide'] = df['Tweets'].isin(["Worldwide", "worldwide", "WorldWide"])
    df
    
    Out[230]:
          Tweets Worldwide
    0  worldwide      True
    1      asdas     False
    2  Worldwide      True
    3  WorldWide      True
    

    但是,我个人认为在规范化推文方面有更多的里程数,因此您可以通过使用 str.lower 将推文小写然后使用 str.contains 来测试推文是否包含您的话来与单一表示进行比较:

    In [231]:
    df['Worldwide'] = df['Tweets'].str.lower().str.contains("worldwide")
    df
    
    Out[231]:
          Tweets Worldwide
    0  worldwide      True
    1      asdas     False
    2  Worldwide      True
    3  WorldWide      True
    

    【讨论】:

      【解决方案2】:

      我有这个作为最终形式: tweets['worldwide'] = tweets['user.location'].str.lower().str.contains("worldwide")

      最终计数出现:

      tweets['worldwide'].value_counts()
      
      
      False    4998
       True      185
       Name: worldwide, dtype: int64
      

      【讨论】:

        猜你喜欢
        • 2018-06-18
        • 2021-09-30
        • 2017-06-20
        • 1970-01-01
        • 2011-03-14
        • 2015-09-03
        • 2013-12-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多