首页 文章

我想在我的pandas数据帧中创建一个value_counts列

提问于
浏览
33

我对R更熟悉,但我想知道是否有办法在熊猫中做到这一点 . 我想从我的一个dataframe列创建唯一值的计数,然后将包含这些计数的新列添加到我的原始数据框 . 我尝试过几种不同的东西 . 我创建了一个pandas系列,然后使用value_counts方法计算计数 . 我试图将这些值合并回原始数据帧,但我要合并的键是在索引(ix / loc)中 . 任何建议或解决方案将不胜感激

Color Value
Red   100
Red   150
Blue  50

我想要回报一些类似的东西

Color Value Counts
Red   100   2
Red   150   2 
Blue  50    1

4 回答

  • 0
    df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
    

    例如,

    In [102]: df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
    
    In [103]: df
    Out[103]: 
      Color  Value
    0   Red    100
    1   Red    150
    2  Blue     50
    
    In [104]: df['Counts'] = df.groupby(['Color'])['Value'].transform('count')
    
    In [105]: df
    Out[105]: 
      Color  Value  Counts
    0   Red    100       2
    1   Red    150       2
    2  Blue     50       1
    

    请注意 transform('count') 忽略NaN . 如果要计算NaN,请使用 transform(len) .


    对于匿名编辑器:如果您在使用 transform('count') 时收到错误,可能是由于您的Pandas版本太旧了 . 以上工作与熊猫版本0.15或更新 .

  • 42

    我最初的想法是使用列表理解,如下所示,但正如评论中指出的那样,这比 groupbytransform 方法慢 . 我将留下这个答案来证明 WHAT NOT TO DO

    In [94]: df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]})
    In [95]: df['Counts'] = [sum(df['Color'] == df['Color'][i]) for i in xrange(len(df))]
    In [96]: df
    Out[100]: 
      Color  Value  Counts
    0   Red    100       2
    1   Red    150       2
    2  Blue     50       1
    
    [3 rows x 3 columns]
    

    对于具有多个列的DataFrame,@ unutbu的方法变得复杂,这使得代码更加简单 . 如果您正在处理一个小数据框,这会更快(见下文),但除此之外,您应该使用 NOT 使用它 .

    In [97]: %timeit df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]}); df['Counts'] = df.groupby(['Color']).transform('count')
    100 loops, best of 3: 2.87 ms per loop
    In [98]: %timeit df = pd.DataFrame({'Color': 'Red Red Blue'.split(), 'Value': [100, 150, 50]}); df['Counts'] = [sum(df['Color'] == df['Color'][i]) for i in xrange(len(df))]
    1000 loops, best of 3: 1.03 ms per loop
    
  • 2

    另一种选择:

    z = df['Color'].value_counts 
    
        z1 = z.to_dict() #converts to dictionary
    
        df['Count_Column'] = df['Color'].map(z1)
    

    此选项将为您提供一个具有重复计数值的列,对应于“颜色”列中每个值的频率 .

  • 1

    df['Counts'] = df.Color.groupby(df.Color).transform('count')

    您可以对任何系列执行此操作:将其自行分组并调用 transform('count')

    >>> series = pd.Series(['Red', 'Red', 'Blue'])
    >>> series.groupby(series).transform('count')
    0    2
    1    2
    2    1
    dtype: int64
    

相关问题