【问题标题】:Pandas: rank() under groupby() returns "ValueError: Wrong number of items passed 2, placement implies 1"Pandas:groupby() 下的 rank() 返回“ValueError:传递的项目数错误 2,位置暗示 1”
【发布时间】:2021-09-30 16:04:13
【问题描述】:

我有以下数据框:

index, col_name, extra_col
1, item_1, stuff
2, item_2, stuff
3, item_3, stuff
4, item_4, stuff
5, item_5, stuff
6, item_6, stuff
7, item_7, stuff
8, item_8, stuff
9, item_9, stuff

我正在对其应用以下转换:

df = df.sort_values(by = 'col_name')
df['yPos'] = np.arange(len(df)) // 3
df['xPos'] = df.groupby(["yPos"]).rank(method='first')-1
df = df.astype({'x': 'int'})

我想在我的数据框xPosyPos 中添加两列。 yPos 专栏工作正常。但是在运行带有xPos 列的行时出现以下错误:

Wrong number of items passed 2, placement implies 1

怎么了?

【问题讨论】:

  • 不可重现,response 未定义。

标签: python pandas dataframe pandas-groupby


【解决方案1】:

当您尝试将代码分配给一列xPos 时,它产生了多列的结果。因此,错误。您可以改为仅在yPos 上排名,以获取xPos 中的相对序列号。

如下更改您的代码:

df = df.sort_values(by = 'col_name')
df['yPos'] = np.arange(len(df)) // 3

df['xPos'] = df.groupby("yPos")['yPos'].rank(method='first')-1
df = df.astype({'xPos': int})

结果:

print(df)

   index col_name extra_col  yPos  xPos
0      1   item_1     stuff     0     0
1      2   item_2     stuff     0     1
2      3   item_3     stuff     0     2
3      4   item_4     stuff     1     0
4      5   item_5     stuff     1     1
5      6   item_6     stuff     1     2
6      7   item_7     stuff     2     0
7      8   item_8     stuff     2     1
8      9   item_9     stuff     2     2

【讨论】:

  • 所以总是需要添加['yPos']?还是仅在特定情况下?
  • @SimonBreton 并不总是需要,但如果您想将其分配给一列,则需要。
  • @SimonBreton Groupby.Rank() 可以对多列进行排名并给出多列的结果。但是,如果您只想根据yPos 进行排名并在xPos 的一列中生成结果,则必须指定要排名的列。这就是逻辑。
猜你喜欢
  • 2021-04-08
  • 2020-01-30
  • 2021-07-13
  • 2021-08-10
  • 2021-07-05
  • 2020-07-02
  • 2021-11-26
  • 2019-09-23
  • 2020-04-22
相关资源
最近更新 更多