【发布时间】:2020-11-21 12:56:36
【问题描述】:
我有一个数据框 df,其中包含 6000 多行数据,日期时间索引采用 YYYY-MM-DD 形式,列 ID、water_level 和 change。
我想:
- 遍历
change列中的每个值并确定转折点 - 当我找到一个转折点时,将包括索引在内的整行数据复制到一个新的数据帧中,例如
turningpoints_df - 对于循环中确定的每个新转折点,将该行数据添加到我的新数据框
turningpoints_df,这样我最终会得到如下结果:
ID water_level change
date
2000-10-01 2 5.5 -0.01
2000-12-13 40 10.0 0.02
2001-02-10 150 1.1 -0.005
2001-07-29 201 12.4 0.01
... ... ... ...
我正在考虑采用定位方法,例如(纯粹是说明性的):
turningpoints_df = pd.DataFrame(columns = ['ID', 'water_level', 'change'])
for i in range(len(df['change'])):
if [i-1] < 0 and [i+1] > 0:
#this is a min point and take this row and copy to turningpoints_df
elif [i-1] > 0 and [i+1] < 0:
#this is a max point and take this row and copy to turningpoints_df
else:
pass
我的问题是,我不确定如何对照之前和之后的值检查change 列中的每个值,然后在满足条件时如何将该行数据提取到新的 df 中.
【问题讨论】:
-
预期输出之前的数据是什么样的? IE。输入是什么?
-
分享源 df 的样本会很有用 (
df..loc[n:m].to_dict())。是一个转折点,与 date 和 ID 无关。即只是df中数据的顺序? -
@RobRaymond 这只是水位的每日时间序列,最后有一个额外的列“变化”记录与上一个条目的水位差异
标签: python pandas loops dataframe conditional-statements