【问题标题】:Adding stats code to a function in Python将统计代码添加到 Python 中的函数
【发布时间】:2016-07-07 13:42:41
【问题描述】:

我对 Python 比较陌生,正在尝试学习如何编写函数。 this post 的答案强调了如何从数据框中获取某些统计信息,我想在函数中使用它。

这是我的尝试,但不适用于AttributeError: 'SeriesGroupBy' object has no attribute 'test_for_B'

 def test_multi_match(df_in,test_val):
    test_for_B = df_in == test_val
    contigious_groups = ((df_in == test_val) & (df_in != df_in.shift())).cumsum() + 1
    counts = df_in.groupby(contigious_groups).test_for_B.sum()
    counts.value_counts() / contigious_groups.max()

有人可以帮忙把这段代码放在一个我可以在其他数据帧上重复使用的函数中吗?谢谢。

编辑:现在已经解决了大属性错误。

【问题讨论】:

  • rng.df_inrng 未在您的代码中的任何位置定义。
  • 错误信息很清楚:在函数的第 3 行调用df.df_in,考虑到函数的输入,这没有多大意义
  • 已更正错字但仍有属性错误'SeriesGroupBy' object has no attribute 'test_for_B'

标签: python pandas


【解决方案1】:

给你:

def repeat_stats(series, var):
    isvar = series == var
    wasntvar = series != series.shift()
    cont_grps = (isvar & wasntvar).cumsum()
    counts = isvar.loc[cont_grps.astype(bool)].groupby(cont_grps).sum()
    return counts.value_counts() / cont_grps.max()

repeat_stats(rng.initial_data, 'B')

3.0    0.5
2.0    0.5
Name: initial_data, dtype: float64

【讨论】:

  • 这太棒了,我可以确认它完全符合我的需要,我还有很多东西要学...谢谢
猜你喜欢
  • 2011-08-11
  • 1970-01-01
  • 2011-08-19
  • 2013-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多