python - Pandas groupby 在重新组装组时更改返回类型

标签 python pandas group-by

我有一个数据框:

df = pd.DataFrame({'c':[0,1,1,2,2,2],   'date':pd.to_datetime(['2016-01-01','2016-02-01','2016-03-01','2016-04-01','2016-05-01','2016-06-01'])})

对于每一行,我想得到一个数字 = 每个日期的月份数(Jan=1,Feb=2 等)+ 该组的长度(第一组有 1 名成员,第二组有 2 名等。 ):

所以它应该返回类似的东西:

c       date   num
0 2016-01-01    2
1 2016-02-01    4
1 2016-03-01    5
2 2016-04-01    7
2 2016-05-01    8
2 2016-06-01    9

我创建了一个函数:

def testlambda(x):
    print(x)
    return x.dt.month.astype('int') + len(x)

并使用了groupby + transform:

df['num'] = df.groupby(['c'])['date'].transform(lambda x: testlambda(x))

但是返回的新列仍然是日期格式,即使我的 lambda 返回 int。

在这里做什么?

最佳答案

尝试使用 DataFrameGroupBy.transform() 而不是 SeriesGroupBy.transform() 因为后者试图将结果转换为源数据类型:

In [131]: def testlambda(x):
     ...:     #print(x)
     ...:     return x.dt.month.astype('int') + len(x)
     ...:

In [132]: df
Out[132]:
   c       date
0  0 2016-01-01
1  1 2016-02-01
2  1 2016-03-01
3  2 2016-04-01
4  2 2016-05-01
5  2 2016-06-01

#                                      v        v - thats's the only difference    
In [133]: df['num'] = df.groupby(['c'])[['date']].transform(lambda x: testlambda(x))

In [134]: df
Out[134]:
   c       date  num
0  0 2016-01-01    2
1  1 2016-02-01    4
2  1 2016-03-01    5
3  2 2016-04-01    7
4  2 2016-05-01    8
5  2 2016-06-01    9

关于python - Pandas groupby 在重新组装组时更改返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41527625/

相关文章:

python - Allcoin 签名的 POST 请求失败

python - 'int' 对象没有属性 '__getitem__'

python - 简单独特的非优先队列系统

sql - 我如何分组连接每一行?

python - 如何正确分组列?

Mysql - 按组排序,从组中选择最新的

python - 使用shell脚本调用多个ROS启动文件

python - 从 python 中的两个列表创建 Pandas df

python - 使用 pandas 数据帧输出调整 ipython 笔记本输出窗口的大小

python - Pandas:如何创建多索引枢轴