np.nan
值填充零,向后填充,然后取第一行并重新分配给原始数据框即可。将原始答案翻译为“最初的回答”。df.iloc[0, :] = df.replace(0, np.nan).bfill().iloc[0, :]
import numpy as np
cols = list(df.columns)
# check if zero exist in string or integer
df2[cols] = df2[cols].replace({0:np.nan})
df[cols] = df[cols].bfill()