【问题标题】:Grouping by date column and applying a function to group by按日期列分组并将函数应用于分组依据
【发布时间】:2019-10-15 11:58:54
【问题描述】:

我之前尝试过问一个问题,但被删除了,以便我可以更清楚地询问并显示我正在尝试的内容(如果它很接近)。

我的样本df是

    day         a   b
  5/11/19       3   1
  5/11/19       4   6
  5/12/19       1   2
  5/12/19       5   9
  5/13/19      11   14

我想按天列分组,并希望有一个新的 df 来计算 col a 和 col b 的值的数量

我正在尝试类似的东西

def calc_(group_df):
result = dict()
result["x"] = group_df[(group_df.x) < 10] / len(group_df.x)
result["y"] = group_df[(group_df.y) < 10] / len(group_df.y)
return pd.Series(result, index=["x", "y"])

然后

df.groupby("day").apply(calc)

但我收到了错误

TypeError:Could not operation 163143 with block values unsupported operand type(s) for /: 'str' and 'int'

我错过了什么吗?

我想要我的最终输出

     day         a   b
  5/11/19       .3  .1
  5/12/19       .5  .9
  5/13/19       .1  .4

我希望它按工作日分组,并希望每个工作日在我的最终输出中只显示一次。

【问题讨论】:

  • 您的数据类型不匹配您将string 除以integer
  • @Chris 谢谢先生,有什么办法可以解决这个问题吗?

标签: python python-3.x pandas data-science data-analysis


【解决方案1】:

我不完全确定你希望你的最终数据框是什么样子,但看起来这是你可以做的。

使用这个数据框作为输入:

       day   a   b
0  5/11/19   3   1
1  5/11/19  11   3
2  5/12/19   5   9
3  5/13/19  11  14

def calc(df):

    len_a_under_10 = (df['a'] < 10).sum() / len(df['a'])
    len_b_under_10 = (df['b'] < 10).sum() / len(df['b'])

    df['a_under_10'] = len_a_under_10
    df['b_under_10'] = len_b_under_10

return df

df.groupby('day').apply(calc)

给予:

       day   a   b  a_under_10  b_under_10
0  5/11/19   3   1         0.5         1.0
1  5/11/19  11   3         0.5         1.0
2  5/12/19   5   9         1.0         1.0
3  5/13/19  11  14         0.0         0.0

【讨论】:

  • 这似乎很接近,但它唯一没有做的就是按天分组,当我尝试这个时,我的最终输出每天都有多行,而我每天只想要一行,确实如此有道理?很抱歉造成混乱
猜你喜欢
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-22
  • 2021-12-07
  • 1970-01-01
  • 1970-01-01
  • 2020-03-10
相关资源
最近更新 更多