带有 join 的 Groupby agg 不会产生预期的输出

2024-06-19

我有如下数据框

   Wash_Month  Wash_Day
0           3         2
1           4         3

预期输出是

#d={'Wash_Month':'Wash_Month/Wash_Day','Wash_Day':'Wash_Month/Wash_Day'}

#df.T.astype(str).groupby(d).agg(','.join)
Out[329]: 
                       0    1
Wash_Month/Wash_Day  3,2  4,3

正如你所看到的,我首先进行转置T.

If we groupby with axis=1并删除T,我期望相同的输出。

df.astype(str).groupby(d,axis=1).agg(','.join)
Out[330]: 
   Wash_Month/Wash_Day
0  Wash_Month,Wash_Day
1  Wash_Month,Wash_Day

输出与预期输出不匹配。有具体问题吗agg with join with groupby of axis=1

由于其他agg功能类似于sum正常工作

df.astype(str).groupby({'Wash_Month':'Wash_Month/Wash_Day','Wash_Day':'Wash_Month/Wash_Day'}, axis=1).sum()
Out[332]: 
   Wash_Month/Wash_Day
0                 32.0 # str 3 + str 2
1                 43.0

关于为什么结果变成 float 而不是 str 检查link https://stackoverflow.com/questions/46751465/how-to-add-string-numbers-in-pandas

感谢你的帮助 :-)


这是一个提示:

def f(x):
    print(x)
    print(type(x))
    return 1

df.astype(str).groupby(d,axis=1).agg(f)

Output:

  Wash_Month Wash_Day
0          3        2
1          4        3
<class 'pandas.core.frame.DataFrame'>

请注意,输出是一个数据帧。

相对于:

def f(x):
    print(x)
    print(type(x))
    return 1

df.T.astype(str).groupby(d).agg(f)

Output:

Wash_Month    3
Wash_Day      2
Name: 0, dtype: object
<class 'pandas.core.series.Series'>
Wash_Month    4
Wash_Day      3
Name: 1, dtype: object
<class 'pandas.core.series.Series'>

每个系列都会调用哪个 f ,因此“join”正在连接列标题。

我无法通过挖掘源代码来解释它,但似乎 groupby 和 astype(str) 导致 agg 在每种情况下都有不同的行为。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

带有 join 的 Groupby agg 不会产生预期的输出 的相关文章

随机推荐