[英]Python Pandas replace a cell containing a string with its above cell
我正在嘗試用上面的單元格替換包含某些字符串的單元格:
試過以下代碼,但需要很長時間並導致錯誤:
row, col = df.shape
for i in range(1,row):
if df.iloc[i,0] == "string":
df.iloc[i,0] = df.iloc[i-1,0]
有沒有更好的方法來實現這一目標? 謝謝。
這類問題的一般結構是df.loc [cond,col] = ...
使用@meW的設置,
df = pd.DataFrame({'col': ['Elephant', 'Grass', 'Parameter', 'Root']})
df.loc[df.col.eq('Parameter'), 'col'] = df.col.shift(1)
col
0 Elephant
1 Grass
2 Grass
3 Root
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.