【问题标题】:if there are multiple dates for an ID then only min and max date should be present as shown如果一个 ID 有多个日期,则只应显示最小和最大日期,如图所示
【发布时间】:2021-08-21 13:44:12
【问题描述】:

我在数据框中有以下格式的数据:

Row_1 AB123, 01-mar-2011, 30-mar-2011, data1, data2 
Row_2 CD123, **01-mar-2011**, 30-mar-2011, data1, data2 
Row_3 CD123, 01-apr-2011, **30-apr-2011**, data1, data2 
Row_4 EF123, 01-nov-2011, 30-nov-2011, data1, data2

需要最后一行是:

Row_1 AB123, 01-mar-2011,30-mar-2011,data1,data2 
Row_2 CD123, **01-mar-2011**,**30-apr-2011**,data1,data2
Row_3 EF123, 01-nov-2011, 30-nov-2011,data1,data2

【问题讨论】:

  • 解释一下你需要什么?你如何获得第二个数据框?为什么Row_3被删除了?
  • 抱歉,第 3 行没有删除。已经编辑过了。需要一个新的数据框,如第二个表所示
  • 你不回答我的问题?使用您想要获得第二个数据框的公式
  • 需要特定 id 的最小日期和最大日期。如果您看到 id 'CD123',则总共有 4 个日期。但只需要最小值和最大值

标签: python dataframe data-science


【解决方案1】:

试试:

df["col2"] = pd.to_datetime(df["col2"])
df["col3"] = pd.to_datetime(df["col3"])

df_out = df.groupby("col1", as_index=False).agg(
    {
        "col2": "min",
        "col3": "max",
        "col4": "first",
        "col5": "first",
    }
)

打印:

    col1       col2       col3   col4   col5
0  AB123 2011-03-01 2011-03-30  data1  data2
1  CD123 2011-03-01 2011-04-30  data1  data2
2  EF123 2011-11-01 2011-11-30  data1  data2

df 已使用:

    col1         col2         col3   col4   col5
0  AB123  01-mar-2011  30-mar-2011  data1  data2
1  CD123  01-mar-2011  30-mar-2011  data1  data2
2  CD123  01-apr-2011  30-apr-2011  data1  data2
3  EF123  01-nov-2011  30-nov-2011  data1  data2

【讨论】:

  • 哇,非常感谢:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多