【问题标题】:The pandas equivalent of 'if' 'else' conditionals to add calculated column to df将计算列添加到 df 的“if”“else”条件的 pandas 等效项
【发布时间】:2019-05-26 23:24:41
【问题描述】:

下表计算文本中的唯一单词(在这种情况下为哈姆雷特的德语文本)。

使用 Pandas,我想添加一个列 ['frequency'] 打印三个答案之一。

  • 如果“计数”列中的值为 ,则频率为 “不常见”

  • 如果“计数”列中的值>10,则频率为 '频繁'

  • 如果“计数”列中的值为 1,则频率为“唯一”

我是 pandas 的新手,所以我最初认为我必须使用“for”循环和“if”“else”。当然,这对我不起作用,在阅读完这篇文章后,我发现您可以使用 .loc[] 代替。干净多了。

我会在下面给出答案,以防其他人非常清楚地需要这个设置。 ???这是我之前使用的表格-

      count                 word  length
0     67223                            0
1         7               deinen       6
2         1          überwachsen      11
3         3                 them       4
4         2            fortunens       9
5         1              flammen       7
6         1    ersäuentsezlichen      17
7         2              alleino       7
8         1             empfehle       8
9         1  beschulöffentlicher      19
10        1         unterthänige      12
11        1                   pr       2
12        1       zurükzutreiben      14
13       38                   wo       2
14        1          schadhaften      11
15        1               ddiese       6
16        1         zurükhaltend      12
17        1                 laim       4
18        1               agents       6

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    之后 - 请忽略第一行,它只给出文本中唯一单词的总数。

    data.loc[data["count"] > 10,  "frequency"] = "frequent"
    data.loc[data["count"] <= 10, "frequency"] = "infrequent"
    data.loc[data["count"] == 1,  "frequency"] = "unique"
    

    结果:

      count                 word  length   frequency
    0     67223                            0    frequent
    1         7               deinen       6  infrequent
    2         1          überwachsen      11      unique
    3         3                 them       4  infrequent
    4         2            fortunens       9  infrequent
    5         1              flammen       7      unique
    6         1    ersäuentsezlichen      17      unique
    7         2              alleino       7  infrequent
    8         1             empfehle       8      unique
    9         1  beschulöffentlicher      19      unique
    10        1         unterthänige      12      unique
    11        1                   pr       2      unique
    12        1       zurükzutreiben      14      unique
    13       38                   wo       2    frequent
    

    【讨论】:

    • 如果您的问题得到解答,请点赞/接受最有帮助的问题。您可以通过单击答案左侧的灰色复选标记将其切换为绿色来执行此操作。谢谢。
    • 所有这些答案都很棒!我给出了发布问题时使用的解决方案。但是我的方法真的很基础,所有这些其他方法都非常有用
    • 在这种情况下,您可以接受自己的答案,如果您喜欢这里发布的所有其他人的话。
    • 感谢您的提示;我不喜欢它胜过其他任何一个,但也可以
    【解决方案2】:

    对于多个条件,考虑使用np.select

    conditions = [data['count'] == 1, data['count'] > 10, data['count'] <= 10]
    choices = ['unique', 'frequent', 'infrequent']
    
    data['frequency'] = np.select(conditions, choices)
    

    conditions 的顺序很重要,因为您不希望 data['count'] &lt;= 10 包含 1 的计数。

    您不妨考虑pd.cutnp.digitize,另请参阅How to map numeric data into categories / bins in Pandas dataframe

    【讨论】:

    • 一如既往地出色,请您指导我找到一个好的 numpy 网络链接,那里不好。谢谢
    • data['count'] == 1 应该在data['count'] &lt;= 10 之前,否则count == 1 也被归类为“不频繁”(当它应该是“唯一”时)。条件的顺序很重要。
    • 我不担心,因为我不是 OP。 :) 我一直是你们@coldspeed 的忠实追随者,如果你和 jpp 可以分享一些好的 numpy 链接,那将非常有帮助。
    • @anky_91 Here is a hopefully instructive starting point :) 至于我是如何/为什么学习的,这主要是出于加快现有 pandas 代码的要求(用 numpy 做同样的事情通常比 pandas 快,因为更少的开销)。主要是文档和其他较旧的答案。
    • @coldspeed,好点子,谢谢。我们可以改变条件的顺序。
    【解决方案3】:

    这是pd.cut 的绝佳用例:

    pd.cut(df['count'], 
           bins=[-np.inf, 1, 10, np.inf], 
           labels=['unique', 'infrequent', 'frequent'])
    
    0       frequent
    1     infrequent
    2         unique
    3     infrequent
    4     infrequent
    5         unique
    6         unique
    7     infrequent
    8         unique
    9         unique
    10        unique
    11        unique
    12        unique
    13      frequent
    14        unique
    15        unique
    16        unique
    17        unique
    18        unique
    Name: count, dtype: category
    Categories (3, object): [unique < infrequent < frequent]
    

    np.select 在另一个答案中的缺点是您需要在选择之前评估所有条件,并且不会随着更多条件进行扩展。

    【讨论】:

      【解决方案4】:

      使用 DataFrame.apply 的另一种替代方法:

      def frequer(wordcnt):
          if wordcnt == 1: return 'unique'
          elif wordcnt >10: return 'frequent'
          else: return 'infrequent'
      
      df['freq'] = df.apply(lambda x: frequer(x['count']),axis=1)
      

      输出:

      【讨论】:

        猜你喜欢
        • 2021-01-28
        • 2021-10-01
        • 2021-10-04
        • 2023-03-24
        • 2020-06-09
        • 2012-12-18
        相关资源
        最近更新 更多