python - 在 Pandas 数据框中创建 value_counts 列

标签 python pandas

我想从我的 Pandas 数据框列中创建一个唯一值的计数,然后将具有这些计数的新列添加到我的原始数据框中。我尝试了几种不同的方法。我创建了一个 pandas 系列,然后使用 value_counts 方法计算计数。我试图将这些值合并回我的原始数据框,但我想要合并的键在 Index(ix/loc) 中。

Color Value
Red   100
Red   150
Blue  50

我想返回类似的东西:

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

最佳答案

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 版本太旧。以上适用于 pandas 0.15 或更高版本。

关于python - 在 Pandas 数据框中创建 value_counts 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17709270/

相关文章:

python - Pandas 日期时间索引的算术运算

python - 使用 matplotlib 修剪尾随 xticks 零

python.exe is not a valid win32 application 突然出现错误

python - django 可以支持按某些列分组同时对其他列求和吗

python - 在 groupby 函数后添加一列

python - 仅在特定行的列上应用 pandas 函数

python - Groupby Pandas 生成多个带条件的字段

python - 用于顺序、条件和修改函数应用的高阶函数?

python - Python : How to fix an [errno 2] when trying to open a text file?

python - 对 CSV 文件中的每四个元素求平均值