【问题标题】:create a new column which is a value_counts of another column in python [duplicate]创建一个新列,它是python中另一列的value_counts [重复]
【发布时间】:2020-10-01 14:33:57
【问题描述】:

我有一个 pandas datafram df 包含一个 column 比如说 x,我想从 x 创建另一个列,它是 value_count 中每个项目的 x

这是我的方法

x_counts= []

for item in df['x']:
    item_count = len(df[df['x']==item])
    x_counts.append(item_count)
    
df['x_count'] = x_counts

这可行,但效率很低。我正在寻找一种更有效的方法来处理这个问题。非常感谢您的方法和建议

【问题讨论】:

  • 检查第二个答案。

标签: python python-3.x pandas dataframe


【解决方案1】:

听起来您正在寻找试图获取 x 中项目数的 groupby 函数 还有许多其他功能驱动的方法,但它们可能在不同的版本中有所不同。 我想你正在寻找加入相同的元素并找到它们的总和

df.loc[:,'x_count']=1 # This will make a new column of x_count to each row with value 1 in it 
aggregate_functions={"x_count":"sum"}
df=df.groupby(["x"],as_index=False,sort=False).aggregate(aggregate_functions) # as_index and sort functions will allow you to choose x separately otherwise it would conside the x column as index column

希望它成功。

【讨论】:

  • 为什么sum 带有1 列?在我看来这里过于复杂了
  • 检查欺骗以获得更好的解决方案,第二个答案。
  • 也是错的,OP需要transform
  • 是的,我知道,当我遇到这个问题时,我尝试过搜索 S/O,但没有任何帮助,所以我不得不想出这个,不推荐,但对新构建的人有帮助对groupby函数的理解
  • groupby 函数未填写确切的行数。它仍在做 value_counts,因此没有填充行
猜你喜欢
  • 2019-07-03
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-28
  • 2021-08-06
相关资源
最近更新 更多