【问题标题】:Python group by and find find first sequence that matches a criterionPython group by 并找到匹配条件的第一个序列
【发布时间】:2020-09-12 07:03:07
【问题描述】:

所以我是一个初学者,我发现了很多关于如何找到第一个序列帽子匹配标准的帖子,但我不知道如何将它与“分组依据”功能结合起来并显示新列。

我需要按“Group”列对数据进行分组,并找到第一个大于 0 的值,并在该组的每一行中重复显示在 now 列中。

输入:

df_input = pd.DataFrame({
    "Group": ["A", "A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C"],
    "Value": [0, 1, 0, 3, 5, 0, 2, 4, 4, 0, 3, 0]
})

输出:

df_output = pd.DataFrame({
    "Group": ["A", "A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C"],
    "Value": [0, 1, 0, 3, 5, 0, 2, 4, 4, 0, 3, 0],
    "First sequence": [1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3]
})

【问题讨论】:

  • 如果组中没有大于1的值怎么办?
  • 另外,请在问题中包含可以复制的数据框示例,而不仅仅是图片。
  • 嗨,欢迎来到 SO!你为什么不看看"How do I ask a good question?"。我认为它可能对您和社区有用。
  • 在您的输出数据框中,A 的每一行都有 1,但 1 不大于 1。

标签: python numpy functional-programming pandas-groupby


【解决方案1】:

以下代码解决了您描述的问题。

import pandas as pd
import numpy as np

df_input = pd.DataFrame({
    "Group": ["A", "A", "A", "A", "A", "B", "B", "B", "B", "C", "C", "C"],
    "Value": [0, 1, 0, 3, 5, 0, 2, 4, 4, 0, 3, 0]
})

def greater_than(array, lower_bound=1):
    condition_fulfiled = (array > lower_bound)
    is_greater = condition_fulfiled.any()

    if is_greater:
        return array[np.argmax(condition_fulfiled)]
    else:
        return None


df_input_grouped = df_input.groupby("Group")
df_input_grouped = df_input_grouped.agg([greater_than])


df_input["First sequence"] = None

for group, value in zip(df_input_grouped.index, df_input_grouped.Value.greater_than):
    df_input["First sequence"][df_input.Group==group] = value

df_input

如果您想从结果data frame 中获得结果,您只需将函数greater_than 更改为

def greater_than(array, lower_bound=1):
    condition_fulfiled = (array >= lower_bound)
    is_greater = condition_fulfiled.any()

    if is_greater:
        return array[np.argmax(condition_fulfiled)]
    else:
        return None

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 2020-06-28
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多