如何在 pandas 中向列中添加值

huangapple go评论100阅读模式
英文:

How to add values into columns in pandas

问题

如何使用pandas数据框架将列X和Y的值添加到X2和Y2中?例如,我想将Brad的X和Y值添加到Anton的X2和Y2列中,将Mikel添加到Brad的X2和Y2列中,以此类推,直到结束。

英文:

如何在 pandas 中向列中添加值

How can I add the values from column X and Y to X2 and Y2 using pandas dataframework? For example I want the X and Y value of Brad to be added into the X2 and Y2 column of Anton and for Mikel to be added to X2 and Y2 of Brad and so on till the end.

答案1

得分: 0

你正在寻找Series.shift()

  1. df['X2'] = df['X'].shift(-1)
  2. df['Y2'] = df['Y'].shift(-1)

请注意,最后一行将为NaN

  1. Player X Y X2 Y2
  2. 0 Anton 49.5 50.5 36.4 44.5
  3. 1 Brad 36.4 44.5 20.3 30.7
  4. 2 Mikel 20.3 30.7 10.0 44.4
  5. 3 Jimmy 10.0 44.4 NaN NaN
英文:

You are looking for Series.shift():

  1. df['X2'] = df['X'].shift(-1)
  2. df['Y2'] = df['Y'].shift(-1)

Note that the last row will be NaN:

  1. Player X Y X2 Y2
  2. 0 Anton 49.5 50.5 36.4 44.5
  3. 1 Brad 36.4 44.5 20.3 30.7
  4. 2 Mikel 20.3 30.7 10.0 44.4
  5. 3 Jimmy 10.0 44.4 NaN NaN

huangapple
  • 本文由 发表于 2023年3月7日 06:19:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定