如何连接“应用”#39;在分组对象上

时间:2014-10-14 12:01:10

标签: python pandas

我有一个数据框,我希望在列d和e定义的组中编辑a和b列中的信息。应用于a和b的过程是:将所有行设置为等于c最小的行。列c,d和e必须保持不变。

我在分组对象上使用apply函数。我使用'reindex'来改变a和b。难以连接,“无法连接非NDFrame对象”

这是我到目前为止的地方:

import pandas as pd

exp = pd.DataFrame({'a':[0,1,2,3,4,5,6,7],
                    'b':[0,1,2,3,4,5,6,7],
                    'c':[7,6,5,4,3,2,1,0],
                    'd':['foo','foo','bar','bar']*2,
                    'e':['scen1']*4 + ['scen2']*4})

grouped = exp.groupby(['d','e'], as_index=False)

sorter = 'c'
cols_overwrite = ['a','b']
cols_keep = ['c','d','e']

def wvmexp(group):
    group = group.sort_index(by=sorter, ascending=True)
    group = group.reset_index(drop=True)
    temp = group[cols_keep]
    group = group[cols_overwrite].reindex([0]*len(group))
    group.index = temp.index
    group = pd.concat(['temp','group'], axis=1)
    return group

result = grouped.apply(wvmexp)

为什么连接失败?有没有更好的方法来处理我所采用的方法(即使用reindex& concatenate)?感谢您的帮助,我意识到这是相当具体的。

正确的输出将是这样的数据帧(排序顺序和索引并不重要):

exp = pd.DataFrame({'a':[1,1,3,3,5,5,7,7],
                    'b':[1,1,3,3,5,5,7,7],
                    'c':[7,6,5,4,3,2,1,0],
                    'd':['foo','foo','bar','bar']*2,
                    'e':['scen1']*4 + ['scen2']*4})

1 个答案:

答案 0 :(得分:1)

您为concat函数提供了字符串而不是数据框对象:在wvmexp函数中执行:

group = pd.concat([temp, group], axis=1)
相关问题