英文:
Calculate a duration of time when the wind speed was continiously higher than previous value
问题
这是您的数据框架,
我想添加一列,显示风速 (Скорость ветра, м/с) 连续高于前一个值的时间(秒)。我的尝试结果不正确,
df['seconds_until'] = df.apply(lambda x: pd.to_datetime(df.loc[(df['Скорость ветра, м/с'] < x['Скорость ветра, м/с']) & (df['DateTime'] > x['DateTime']), 'DateTime'].min()) - pd.to_datetime(x['DateTime']), axis=1)
df
英文:
here is my dataframe,
I want to add a new column, which shows how long (seconds) the wind speed (Скорость ветра, м/с) was continuously greater than previous value. What i tried is working wrong,
df['seconds_until'] = df.apply(lambda x: pd.to_datetime(df.loc[(df['Скорость ветра, м/с'] < x['Скорость ветра, м/с']) & (df['DateTime'] > x['DateTime']), 'DateTime'].min()) - pd.to_datetime(x[
'DateTime']), axis=1)
df
答案1
得分: 1
你可以使用以下代码:
group = df['Скорость ветра, м/с'].diff().lt(0).cumsum()
g = df.groupby(group)['Date'].transform
df['duration'] = g('max') - g('min')
请注意,代码中的变量名和函数名未翻译,保持原样。
英文:
You can use:
Code:
group = df['Скорость ветра, м/с'].diff().lt(0).cumsum()
g = df.groupby(group)['Date'].transform
df['duration'] = g('max')-g('min')
答案2
得分: 1
我使用了一个掩码来识别风速的增加。接下来,我累积风速并在0上重置。
df=pd.read_csv("https://raw.githubusercontent.com/vega/vega/main/docs/data/seattle-weather.csv",parse_dates=["date"])
df.set_index("date",inplace=True)
df=df.sort_index()
df.columns
df["mark"]=df.wind.shift(1)<df.wind
df["wind_incr"]=df.wind.mask(~df.mark,0)
prev_accum=0
accum=0
for index,row in df.iterrows():
if row.wind_incr>prev_accum:
accum+=row.wind_incr
else:
accum=0
df.loc[index,"accumulative"]=accum
prev_accum=accum
df["accumulative"].plot()
plt.show()
这是您提供的代码的翻译部分。
英文:
I used a mask to identify increasing wind speeds. Next, I accumulate the wind speeds and reset on 0
df=pd.read_csv("https://raw.githubusercontent.com/vega/vega/main/docs/data/seattle-weather.csv",parse_dates=["date"])
df.set_index("date",inplace=True)
df=df.sort_index()
df.columns
df["mark"]=df.wind.shift(1)<df.wind
df["wind_incr"]=df.wind.mask(~df.mark,0)
prev_accum=0
accum=0
for index,row in df.iterrows():
if row.wind_incr>prev_accum:
accum+=row.wind_incr
else:
accum=0
df.loc[index,"accumulative"]=accum
prev_accum=accum
df["accumulative"].plot()
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论