python - 基于Python Pandas DataFrame中日期的值计算?

标签 python pandas dataframe date

我有如下客户协议(protocol)的 DataFrame:

rng = pd.date_range('2020-12-01', periods=5, freq='D')
df = pd.DataFrame({ "ID" : ["1", "2", "1", "2", "2"],
                   "value" : [100, 200, 300, 400, 500],
                   "status" : ["active", "finished", "active", "finished", "active"],
                   "Date": rng})

我需要根据上面的 df 计算创建新的 DataFrame:

  1. New1 = 状态为“有效”的最后一个协议(protocol)的值
  2. New2 = 状态为“完成”的最后一个协议(protocol)的值

为了更精确,我需要像下面这样创建 df:

enter image description here

最佳答案

尝试使用这么长的时间:

df1 = df.loc[df['status'] == "active"]
df2 = df.loc[df['status'] == "finished"]
df1 = df1.groupby("ID")['value'].last()
df2 = df2.groupby("ID")['value'].last()
IDs = df["ID"].drop_duplicates()
new_df = pd.DataFrame({"ID": IDs, "New1": df1.reindex(IDs).tolist(), "New2": df2.reindex(IDs).tolist()})
print(new_df)

输出:

  ID  New1   New2
0  1   300    NaN
1  2   500  400.0

关于python - 基于Python Pandas DataFrame中日期的值计算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65322384/

相关文章:

python - Pandas 在 iloc Nulls 上设置值

python - 将 Python Pandas 数据框行与加法结合起来

Python Pandas 在中心指示器后去除字母 "|"

python - 识别音乐拍号21

python - 如何将 Pylint 或其他 linters 与 Jupyter 笔记本一起使用?

python - 如何合并这两列? Pandas

python-3.x - 两个数据帧中每个值的 bool 比较

python - 在python中创建XML文件节点丢失

python - 过滤 df 中的行并在字符串值之间返回 - pandas

python - Pandas 应用函数将多个值返回到 Pandas 数据框中的行