在 pandas 中创建一列,该列中包含每天的平均损失值,放在列的最后一行。

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月10日 18:49:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/76217508.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定