1 回答
TA贡献1777条经验 获得超10个赞
以下代码按照您的描述解决了您的问题。
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
添加回答
举报