使用pandas将单元格的值替换为下方单元格中的值

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

Replace value of cell with value in cell below pandas

问题

我想要将包含“Loan fee:”的单元格在“Loan”列中替换为下面单元格中的值。

例如,期望的输出将是:

  1. df = pd.DataFrame([['Lukas Mai', 22, 'End of loan'],
  2. ['Malik Tillman', 20, 'loan transfer'],
  3. ['Abdou Diallo', 26, '€1.50m'],
  4. ['', '', '€1.50m'],
  5. ['Ilaix Moriba', 19, 'End of loan'],
  6. ['Diogo Leite', 23, '€500k'],
  7. ['', '', '€500k'],
  8. ], columns=['Player', 'Age', 'Loan'])

这在pandas中是可以实现的。

英文:

I have a dataframe:

  1. df = pd.DataFrame([['Lukas Mai', 22, 'End of loan'],
  2. ['Malik Tillman', 20, 'loan transfer'],
  3. ['Abdou Diallo', 26, 'Loan fee:'],
  4. ['', '', '€1.50m'],
  5. ['Ilaix Moriba', 19, 'End of loan'],
  6. ['Diogo Leite', 23, 'Loan fee:'],
  7. ['', '', '500k'],
  8. ], columns=['Player', 'Age', 'Loan'])

I want to replace the cells containing "Loan fee:" in the Loan column with the value in the cell below.

For example, the desired output would be:

  1. df = pd.DataFrame([['Lukas Mai', 22, 'End of loan'],
  2. ['Malik Tillman', 20, 'loan transfer'],
  3. ['Abdou Diallo', 26, '€1.50m'],
  4. ['', '', '€1.50m'],
  5. ['Ilaix Moriba', 19, 'End of loan'],
  6. ['Diogo Leite', 23, '€500k'],
  7. ['', '', '€500k'],
  8. ], columns=['Player', 'Age', 'Loan'])

I have looked for similar questions on stackoverflow but haven't found any to answer this question.

Is this possible to do in pandas?

答案1

得分: 0

  1. import numpy as np
  2. df['Loan'] = np.where(df['Loan'] == 'Loan fee:', df['Loan'].shift(-1), df['Loan'])
英文:

Use np.where with pd.Series.shift

  1. import numpy as np
  2. df['Loan'] = np.where(df['Loan'] == 'Loan fee:', df['Loan'].shift(-1), df['Loan'])
  3. Player Age Loan
  4. 0 Lukas Mai 22 End of loan
  5. 1 Malik Tillman 20 loan transfer
  6. 2 Abdou Diallo 26 1.50m
  7. 3 1.50m
  8. 4 Ilaix Moriba 19 End of loan
  9. 5 Diogo Leite 23 500k
  10. 6 500k

huangapple
  • 本文由 发表于 2023年2月8日 22:01:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386883.html
匿名

发表评论

匿名网友

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

确定