我想从我的 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/