更新时间:2023-02-26 12:44:00
使用groupby
.这至少应该比循环遍历所有行更有效率.
Use groupby
. This should at least be more efficient than looping through all rows.
df = pd.DataFrame({'CarNumber': [303] * 4 + [404] * 2 + [405] * 5,
'othercol': range(11)})
def zero_row(cols, idx):
return pd.DataFrame([[0] * len(cols)], columns=cols, index=[idx])
def add_zero_row(x):
return x.append(zero_row(x.columns, x.index.max() + 0.5))
df = df.groupby('CarNumber').apply(add_zero_row)
# remove extra index from grouping
df = df.reset_index('CarNumber', drop=True)
# get rid of last zero row
df.iloc[:-1]