我有一个数据集,我想添加一个列来表示某些计算的结果(这很复杂),计算需要在每个组中进行,每个行的值都依赖于它上面的行。下面是一个简单的示例,说明我目前所掌握的代码和所需的输出:
编辑1 所以我更新了下面的代码,也许我不明白apply是如何工作的,但我认为这将执行两次(每组一次)。然后,我的函数将循环遍历这些执行中的每一行。我仍然不明白为什么它要打印3次…我以为“执行”会打印5次。有什么想法?在
编辑2 我的返回函数的缩进错误。那就修好了。谢谢你的帮助!在
import pandas as pd
df = pd.DataFrame({'type' : ['foo', 'foo', 'foo', 'bar','bar'], 'cost' : [1, 4, 2, 8,9]})
df['class'] = np.nan
def customFunction(test_df):
print np.shape(test_df)
iteration = 1
for currRow in test_df.iterrows():
print 'executed'
if iteration == 1:
test_df['class'] = 'first'
else:
if currRow[1]['cost'] > priorCost:
test_df['class'] = 'greater'
elif currRow[1]['cost'] < priorCost:
test_df['class'] = 'less'
else:
test_df['class'] = 'equal'
iteration += 1
priorCost = currRow[1]['cost']
return test_df
grouped_df = df.groupby(['type']).apply(customFunction)
输出:
^{pr2}$
我会尽我所能给你-我现在需要休息一下,但是:
给我(因为
^{pr2}$diff()
计算了w.r.t.列中第一个条目的差异)所以这包含了你需要的所有信息。目前,我正在努力将这些信息合并回原始数据帧。
df['differences'] = test
造成了巨大的混乱。在更新
我快到了:
因此,唯一需要的是泛型表达式,而不是
test[1].append(test[0])
。也许有人能插手进来?在更新2
回复您的评论:每当您为
apply()
定义函数时,如您可以访问所有标准pandas函数和函数内的整个组。因此,您可以创建所有复杂的依赖于行的魔法,不管它是什么。唯一需要注意的是:},它的条目数与{}的行数一样多。只要返回这样的
someValues
必须是一个只有一列的Series
或{someValues
,就可以始终执行df['resultOfSomethingComplicated'] = df.groupby(level=0).apply(compareSomethingWithinAGroup)
,并使用响应中的所有行。在相关问题 更多 >
编程相关推荐