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

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

Replace value of cell with value in cell below pandas

问题

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

例如,期望的输出将是:

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

这在pandas中是可以实现的。

英文:

I have a dataframe:

df = pd.DataFrame([['Lukas Mai', 22, 'End of loan'],
                   ['Malik Tillman', 20, 'loan transfer'],
                   ['Abdou Diallo', 26, 'Loan fee:'],
                   ['', '', '€1.50m'],
                   ['Ilaix Moriba', 19, 'End of loan'],
                   ['Diogo Leite', 23, 'Loan fee:'],
                   ['', '', '500k'],
                  ], 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:

df = pd.DataFrame([['Lukas Mai', 22, 'End of loan'],
                   ['Malik Tillman', 20, 'loan transfer'],
                   ['Abdou Diallo', 26, '€1.50m'],
                   ['', '', '€1.50m'],
                   ['Ilaix Moriba', 19, 'End of loan'],
                   ['Diogo Leite', 23, '€500k'],
                   ['', '', '€500k'],
                  ], 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

import numpy as np

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

Use np.where with pd.Series.shift

import numpy as np


df['Loan'] = np.where(df['Loan'] == 'Loan fee:', df['Loan'].shift(-1), df['Loan'])

          Player Age           Loan
0      Lukas Mai  22    End of loan
1  Malik Tillman  20  loan transfer
2   Abdou Diallo  26         €1.50m
3                            €1.50m
4   Ilaix Moriba  19    End of loan
5    Diogo Leite  23           500k
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:

确定