根据前几行在数据框中插入行
Inserting rows in dataframe based on previous rows
我需要根据列周插入行,在某些情况下,我在数据框中间缺少周,我想插入行以填充缺失的行作为最后一个现有行的副本,在本例是第 8 周的副本,但列 week 具有增量值:
on this table you can see the jump from week 8 to 12
完美的输出如下:
the final table with incremental values in column week the correct way
下面是我的代码,它只插入了一行 11
for f in range(1, 52 , 1):
if final.iat[i,8]== f and final.iat[i-1,8] != f-1 :
if final.iat[i,8] > final.iat[i-1,8] and final.iat[i,8] != (final.iat[i-1,8] - 1):
line = final.iloc[i-1]
c1 = final[0:i]
c2 = final[i:]
c1.loc[i]=line
concatinated = pd.concat([c1, c2])
concatinated.reset_index(inplace=True)
concatinated.iat[i,11] = concatinated.iat[i-1,11]
concatinated.iat[i,9]= f-1
finaltemp = finaltemp.append(concatinated)```
构建周的完整列表并使用 pd.merge
然后向前填充以替换 NaN
:
weeks = range(df['Week'].min(), df['Week'].max()+1)
out = pd.merge(df, pd.Series(weeks, name='Week'), how='right').ffill()
>>> out
index type Project Week Cumulated Hours Remaining hours
0 XXY 1.0 A 7 18.0 2000.0
1 XXY 1.0 A 8 20.0 1900.0
2 XXY 1.0 A 9 20.0 1900.0
3 XXY 1.0 A 10 20.0 1900.0
4 XXY 1.0 A 11 20.0 1900.0
5 XXY 1.0 A 12 24.0 1500.0
6 XXY 1.0 A 13 36.0 1400.0
我需要根据列周插入行,在某些情况下,我在数据框中间缺少周,我想插入行以填充缺失的行作为最后一个现有行的副本,在本例是第 8 周的副本,但列 week 具有增量值: on this table you can see the jump from week 8 to 12
完美的输出如下: the final table with incremental values in column week the correct way
下面是我的代码,它只插入了一行 11
for f in range(1, 52 , 1):
if final.iat[i,8]== f and final.iat[i-1,8] != f-1 :
if final.iat[i,8] > final.iat[i-1,8] and final.iat[i,8] != (final.iat[i-1,8] - 1):
line = final.iloc[i-1]
c1 = final[0:i]
c2 = final[i:]
c1.loc[i]=line
concatinated = pd.concat([c1, c2])
concatinated.reset_index(inplace=True)
concatinated.iat[i,11] = concatinated.iat[i-1,11]
concatinated.iat[i,9]= f-1
finaltemp = finaltemp.append(concatinated)```
构建周的完整列表并使用 pd.merge
然后向前填充以替换 NaN
:
weeks = range(df['Week'].min(), df['Week'].max()+1)
out = pd.merge(df, pd.Series(weeks, name='Week'), how='right').ffill()
>>> out
index type Project Week Cumulated Hours Remaining hours
0 XXY 1.0 A 7 18.0 2000.0
1 XXY 1.0 A 8 20.0 1900.0
2 XXY 1.0 A 9 20.0 1900.0
3 XXY 1.0 A 10 20.0 1900.0
4 XXY 1.0 A 11 20.0 1900.0
5 XXY 1.0 A 12 24.0 1500.0
6 XXY 1.0 A 13 36.0 1400.0