【问题标题】:Strange Behavior With Pandas Group By - Transform On String ColumnsPandas Group By 的奇怪行为 - 对字符串列进行转换
【发布时间】:2021-06-03 09:43:33
【问题描述】:

我在使用 .transform() 的 Pandas .groupby() 中遇到了一个奇怪的行为。下面是生成数据集的代码:

df = pd.DataFrame({"Name" : ["Alice", "Bob", "Mallory", "Mallory", "Bob" , "Mallory"] ,
                   "Random_Number": [1223344, 373293832, 32738382392, 7273283232, 8239329, 23938832],
                   "City" : ["Seattle", "Seattle", "Portland", "Seattle", "Seattle", "Portland"]})

这是我为 transform() 编写的函数。

# this function will attach each value in string col with the number of elements in the each city group
# if the col type is not an object, then return 0 for all rows. 

def some(x): 
    if x.dtype == 'object':
        return x + '--' + str(len(x))
    else:
        return 0

然后我将我的函数与转换一起使用 - 完美运行并得到我想要的。

df_2 = stack.groupby(["City"])['Name','Random_Number'].transform(some)

但是,当我将 col 的顺序从 ['Name','Random_Number'] 切换到 ['Random_Number','Name'] 时发生了奇怪的事情

df_2 = stack.groupby(["City"])['Random_Number','Name'].transform(some)

当您查看 'Name' 列中的单元格时,似乎 pandas 将所有内容多次放入一个单元格:

df_2.iloc[0,1]
# Return: 
# 0      Alice--4
# 1        Bob--4
# 3    Mallory--4
# 4        Bob--4
# Name: Name, dtype: object

为什么会这样?

【问题讨论】:

标签: python pandas transform


【解决方案1】:

问题在于您的return

如果x.dtype == 'object' 则返回一个系列,因此您的transform 聚合不会减少(返回的长度与原始长度相同)。如果它采用另一条路径,则返回单个标量 0,pandas 将其视为减少(返回是每个组的单个值)。

因为您的聚合在减少方面有所不同,所以 pandas 用于确定要采取的路径以及如何将其带回原始 DataFrame 的内部结构会根据您的列顺序而感到困惑。当'Random_Number' 是第一个时,它会检查函数,发现函数归约并采用一条路径,但如果'Name' 首先出现,它会检查,发现函数没有归约并采用另一条路径进行计算。

您可以通过确保两个回报不减少

来解决此问题
def some(x): 
    if x.dtype == 'object':
        return x + '--' + str(len(x))
    else:
        return [0]*len(x)

df.groupby('City')[['Random_Number','Name']].transform(some)
#   Random_Number        Name
#0              0    Alice--4
#1              0      Bob--4
#2              0  Mallory--2
#3              0  Mallory--4
#4              0      Bob--4
#5              0  Mallory--2

df.groupby('City')[['Name', 'Random_Number']].transform(some)
#         Name  Random_Number
#0    Alice--4              0
#1      Bob--4              0
#2  Mallory--2              0
#3  Mallory--4              0
#4      Bob--4              0
#5  Mallory--2              0

【讨论】:

  • 哇,就是这个原因!太感谢了!现在我明白了!
猜你喜欢
  • 1970-01-01
  • 2020-01-22
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
相关资源
最近更新 更多