英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论