Loading [MathJax]/jax/input/TeX/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >Python Pandas -将groupby函数的结果返回到父表

Python Pandas -将groupby函数的结果返回到父表
EN

Stack Overflow用户
提问于 2013-07-09 13:34:19
回答 1查看 1.6K关注 0票数 1

使用Python3我使用pandas读取csv文件,对数据帧进行分组,对分组后的数据应用函数,然后将这些结果添加回原始数据帧。

我的输入如下所示:

代码语言:javascript
运行
AI代码解释
复制
email                   cc  timebucket  total_value
john@john.com           us  1           110.50
example@example.com     uk  3           208.84
...                     ... ...         ...

基本上,我尝试按cc分组,并计算该组中total_value中每个值的百分位数排名。其次,我想对这些结果应用一个流语句。我需要将这些结果添加回原始/父DataFrame。这样它看起来就像这样:

代码语言:javascript
运行
AI代码解释
复制
email                   cc  timebucket  total_value     percentrank rankbucket
john@john.com           us  1           110.50          48.59       mid50
example@example.com     uk  3           208.84          99.24       top25
...                     ... ...         ...             ...         ...

下面的代码给了我一个AssertionError,我不知道为什么。我对Python和pandas非常陌生,所以这可能会解释它们之间的关系。

代码:

代码语言:javascript
运行
AI代码解释
复制
import pandas as pd
import numpy as np
from scipy.stats import rankdata

def percentilerank(frame, groupkey='cc', rankkey='total_value'):
    from pandas.compat.scipy import percentileofscore

    # Technically the below percentileofscore function should do the trick but I cannot
    # get that to work, hence the alternative below. It would be great if the answer would
    # include both so that I can understand why one works and the other doesnt.
    # func = lambda x, score: percentileofscore(x[rankkey], score, kind='mean')

    func = lambda x: (rankdata(x.total_value)-1)/(len(x.total_value)-1)*100
    frame['percentrank'] = frame.groupby(groupkey).transform(func)


def calc_and_write(filename):
    """
    Function reads the file (must be tab-separated) and stores in a pandas DataFrame.
    Next, the percentile rank score based is calculated based on total_value and is done so within a country.
    Secondly, based on the percentile rank score (prs) a row is assigned to one of three buckets:
        rankbucket = 'top25' if prs > 75
        rankbucket = 'mid50' if 25 > prs < 75
        rankbucket = 'bottom25' if prs < 25
    """

    # Define headers for pandas to read in DataFrame, stored in a list
    headers = [
        'email',            # 0
        'cc',               # 1
        'last_trans_date',  # 3
        'timebucket',       # 4
        'total_value',      # 5
    ]

    # Reading csv file in chunks and creating an iterator (is supposed to be much faster than reading at once)
    tp = pd.read_csv(filename, delimiter='\t', names=headers, iterator=True, chunksize=50000)
    # Concatenating the chunks and sorting total DataFrame by booker_cc and total_nett_spend
    df = pd.concat(tp, ignore_index=True).sort(['cc', 'total_value'], ascending=False)

    percentilerank(df)

编辑:按照要求,这是回溯日志:

代码语言:javascript
运行
AI代码解释
复制
Traceback (most recent call last):
  File "C:\Users\m\Documents\Python\filter_n_split_3.py", line 85, in <module>
    print(calc_and_write('tsv/test.tsv'))
  File "C:\Users\m\Documents\Python\filter_n_split_3.py", line 74, in calc_and_write
    percentilerank(df)
  File "C:\Users\m\Documents\Python\filter_n_split_3.py", line 33, in percentilerank
    frame['percentrank'] = frame.groupby(groupkey).transform(func)
  File "C:\Python33\lib\site-packages\pandas\core\groupby.py", line 1844, in transform
    axis=self.axis, verify_integrity=False)
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 894, in concat
    verify_integrity=verify_integrity)
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 964, in __init__
    self.new_axes = self._get_new_axes()
  File "C:\Python33\lib\site-packages\pandas\tools\merge.py", line 1124, in _get_new_axes
    assert(len(self.join_axes) == ndim - 1)
AssertionError
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-07-09 15:15:13

尝尝这个。您的示例从转换函数返回一个Series,但应该返回单个值。(这使用pandas排名函数FYI)

代码语言:javascript
运行
AI代码解释
复制
In [33]: df
Out[33]: 
                 email  cc  timebucket  total_value
0        john@john.com  us           1       110.50
1  example@example.com  uk           3       208.84
2          foo@foo.com  us           2        50.00

In [34]: df.groupby('cc')['total_value'].apply(lambda x: 100*x.rank()/len(x))
Out[34]: 
0    100
1    100
2     50
dtype: float64

In [35]: df['prank'] = df.groupby('cc')['total_value'].apply(lambda x: 100*x.rank()/len(x))

In [36]: df
Out[36]: 
                 email  cc  timebucket  total_value  prank
0        john@john.com  us           1       110.50    100
1  example@example.com  uk           3       208.84    100
2          foo@foo.com  us           2        50.00     50
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17549596

复制
相关文章
Java中对map按key或val排序
Collections是一个工具类,sort是其中的静态方法,是用来对List类型进行排序的,它有两种参数形式:
sunonzj
2022/06/21
1.6K0
int a; int* a; int** a; int (*a)[]; int (*a)(int)
a) int a;表示一个内存空间,这个空间用来存放一个整数(int); b) int* a;表示一个内存空间,这个空间用来存放一个指针,这个指针指向一个存放整数的空间,即a)中提到的空间; c) int** a;表示一个内存空间,这个空间用来存放一个指针,这个指针指向一个存放指针的空间,并且指向的这个空间中的指针,指向一个整数。也简单的说,指向了一个b)中提到的空间; d) int (*a)[4];表示一个内存空间,这个空间用来存放一个指针,这个指针指向一个长度为4、类型为int的数组;和int** a的区别在于,++、+=1之后的结果不一样,其他用法基本相同。 以上四种类型见上图表示。 e) int (*a)(int);表示一个内存空间,这个空间用来存放一个指针,这个指针指向一个函数,这个函数有一个类型为int的参数,并且函数的返回类型也是int。
Twcat_tree
2022/11/30
2.3K0
int a; int* a; int** a; int (*a)[]; int (*a)(int)
lombok的val
今天遇到一个情况,我们知道把java代码粘贴到kt文件里,idea会自动转换java为kt
阿超
2023/02/22
9630
lombok的val
listnode.val java(string indexof方法)
有一列 1.给出 Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) 要求 Output: 7 -> 0 -> 8
全栈程序员站长
2022/08/01
6450
Train / Val / Test划分
合理的Train/Test集划分会有效地减少under-fitting和over-fitting现象
mathor
2020/01/15
2.2K0
VBA专题:Val函数
Val函数返回作为参数传递的字符串中的前导数字,它在无法识别为数字部分的第一个字符处停止读取字符串,但它不会在空格处停止。
fanjy
2022/11/16
1.5K0
jquery的html,text,val
.html()用为读取和修改元素的HTML标签 .text()用来读取或修改元素的纯文本内容 .val()用来读取或修改表单元素的value值。 这三个方法功能上的对比 .html(),.text(),.val()三种方法都是用来读取选定元素的内容;只不过.html()是用来读取元素的HTML内容(包括其Html标签),.text()用来读取元素的纯文本内容,包括其后代元素,.val()是用来读取表单元素的"value"值。其中.和.text()方法不能使用在表单元素上,而.val()只能使用在表单元素上;
marsggbo
2018/01/23
2K0
jquery的html,text,val
    1.html()用为读取和修改元素的HTML标签     2.text()用来读取或修改元素的纯文本内容     3.val()用来读取或修改表单元素的value值。
ydymz
2018/09/10
1.6K0
int(*p)[4] int*p[4]
1、int(*p)[4];------p为指向含4个元素的一维整形数组的指针变量(是指针) #include <stdio.h> #include <stdlib.h> int main() { int a[4]={1,2,3,4}; int (*p)[4]; p=&a; printf("%d\n",(*p)[3]); printf("%d\n",*p); return 0; } 2、int *p[4];-------定义指针数组p,它由4个指向整型数据的
谙忆
2021/01/19
2K0
java中string转换为int(int char)
// String change int public static void main(String[] args) { String str = “123”; int n; // first method // n = Integer.parseInt(str); n = 0; n = Integer.parseInt(str); System.out.println(“Integer.parseInt(str):”+ n); System.out.println(“\n”); //second method //n = Integer.valueOf(str).intValue();
全栈程序员站长
2022/07/28
1.9K0
java中string转换为int(int char)
JAVA将string转化为int(int怎么转string)
1). int i = Integer.parseInt([String]); 或
全栈程序员站长
2022/07/28
3K0
C# int int16 Int32 Int64的介绍[通俗易懂]
今天看到别人的代码中用到Int32,UInt32相关,想到自己平时用的都是int类型整数,就心生好奇的翻了一下资料:
全栈程序员站长
2022/09/21
3.6K0
.net Int16 、(int Int32)、 Int64 的区别
摘要: 关于什么是16位整数,32位整数,64位整数,请看这里:http://www.cnblogs.com/EasonJim/p/4837061.html Int16 值类型表示值介于 -32768 到 +32767 之间的有符号整数。
拓荒者
2019/03/14
2.7K0
int是什么_int a[4][4]
Int16 意思是16位整数(16bit integer),相当于short 占2个字节 -32768 ~ 32767
全栈程序员站长
2022/09/21
1.4K0
聊聊kotlin的val跟var
val:英文读value,代表是immutable, 只读的意思 比如下面这个kotlin代码
韦东锏
2021/09/29
1.2K0
聊聊kotlin的val跟var
2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int
2022-05-26:void add(int L, int R, int C)代表在arrL...R上每个数加C,
福大大架构师每日一题
2022/05/26
1.5K0
2022-05-26:void add(int L, int R, int C)代表在arr[L...R]上每个数加C, int get(int L, int
#define a int[10]与 typedef int a[10]用法
// #define a int[10] #include <stdio.h> #include <stdlib.h> #define a int[10] int main() { int *p=(int *)malloc(sizeof(a)); p[0]=1; printf("%d\n",p[0]); return 0; } // typedef int a[10]; #include <stdio.h> typedef int a[10]; int m
Daotin
2018/08/31
1.6K0
Android逆向之旅---动态方式破解apk进阶篇(IDA调试so源码)[转]include <stdio.h>int func(int a, int b, int c, int d, int e,
声明:本文转自Android逆向之旅---动态方式破解apk进阶篇(IDA调试so源码),此文干货很多。
用户2930595
2018/08/23
4.2K0
Android逆向之旅---动态方式破解apk进阶篇(IDA调试so源码)[转]include <stdio.h>int func(int a, int b, int c, int d, int e,
JAVA 枚举 String-int
/** * @author 姜兴琪 */ package cn.bycs.online.dealer.vo; /** * @author jiangxingqi * 车辆状态枚举 */ public enum NewCarStatusEnum { DRAFT("草稿",1), SUBMIT_RELEASE("提交发布",2), PUBLISH_SUCCESS("发布成功",3), AUDIT_DENY("审核不通过",4); private St
week
2018/08/27
3440
点击加载更多

相似问题

基本Regex需要帮助

15

需要Python Regex帮助(基本)

42

需要C语言的基本帮助

26

需要帮助来完成连接

10

需要帮助理解基本递归问题

16
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档