英文:
Create a column with avg loss per day value in last row of the column-pandas
问题
Here's the translated code part without the translation of the code itself:
df['Avg loss per day'] = (df['水位'].iloc[0] - df['水位'].iloc[6]) / 7
df = df.round({'Avg loss per day': 2})
df.loc[0:6, ['Avg loss per day']] = np.nan
This code calculates the average water level loss per day and sets NaN values in the 'Avg loss per day' column for the first six rows.
英文:
Day water level Avg loss per day
1 100 NaN
2 90 NaN
3 88 NaN
4 87 NaN
5 77 NaN
6 75 NaN
7 74 (100-74)/7
I want to find the average water level loss per day in the third column of this dataframe.
Only the last row should have value and the rest 6 rows above should have NAN.
I tried using .iloc
and np.nan
.
df['Avg loss per day']=(df['water level'].iloc[0]-df['water level'].iloc[6])/7
df = df.round({'Avg loss per day': 2})
df.loc[0:6,['Avg loss per day']]=np.nan
but its throwing error.
Is there any other way to do it without using iloc
答案1
得分: 1
你可以使用以下代码:
df['Avg loss per day'] = df['water level'].shift(6).sub(df['water level']).div(7)
或者,如果 "Avg loss per day" 最初不存在或为空:
df.loc[df.index[-1], 'Avg loss per day'] = (df['water level'].iloc[0] - df['water level'].iloc[-1]) / 7
输出:
Day water level Avg loss per day
0 1 100 NaN
1 2 90 NaN
2 3 88 NaN
3 4 87 NaN
4 5 77 NaN
5 6 75 NaN
6 7 74 3.714286
英文:
You could use:
df['Avg loss per day'] = df['water level'].shift(6).sub(df['water level']).div(7)
Or, if "Avg loss per day" is initially non-existent or empty:
df.loc[df.index[-1],
'Avg loss per day'] = (df['water level'].iloc[0]
-df['water level'].iloc[-1])/7
Output:
Day water level Avg loss per day
0 1 100 NaN
1 2 90 NaN
2 3 88 NaN
3 4 87 NaN
4 5 77 NaN
5 6 75 NaN
6 7 74 3.714286
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论