Pandas Dataframe groupby:一次应用多个lambda函数

时间:2019-02-07 12:10:18

标签: python pandas

我将以下pandas数据框按“名称”分组,然后对“值”应用几个lambda函数以生成其他列。 是否可以一次应用这些lambda函数以提高效率?

public class XLSXToCSVConverter {

    public InputStream convertxlstoCSV(InputStream inputStream) throws IOException, InvalidFormatException {

        Workbook wb = WorkbookFactory.create(inputStream);

        return  csvConverter(wb.getSheetAt(0));
    }

    private InputStream csvConverter(Sheet sheet) {
        Row row = null;
        String str = new String();
        for (int i = 0; i < sheet.getLastRowNum()+1; i++) {
            row = sheet.getRow(i);
            String rowString = new String();
            for (int j = 0; j < 3; j++) {
                if(row.getCell(j)==null) {
                    rowString = rowString + Utility.BLANK_SPACE + Utility.COMMA;
                }
                else {
                    rowString = rowString + row.getCell(j)+ Utility.COMMA;
                }
            }
            str = str + rowString.substring(0,rowString.length()-1)+ Utility.NEXT_LINE_OPERATOR;
        }
        System.out.println(str);
        return new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
    }
}

输出:

import pandas as pd

df = pd.DataFrame({'name': ['A','A', 'B','B','B','B', 'C','C','C'], 
                   'value': [1, 3, 1, 2, 3, 1, 2, 3, 3], })

df['Diff'] = df.groupby('name')['value'].transform(lambda x: x - x.iloc[0])
df['Count'] = df.groupby('name')['value'].transform(lambda x: x.count())
df['Index'] = df.groupby('name')['value'].transform(lambda x: x.index - x.index[0] + 1)

print(df)

1 个答案:

答案 0 :(得分:3)

这里可以将GroupBy.apply与一个功能一起使用,但不确定是否有更好的性能:

org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine