【发布时间】: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
为什么会这样?
【问题讨论】:
-
这不是您更改列顺序的方式。例如,
df = df[df.columns[new_order]]从回答到问题stackoverflow.com/q/13148429/5660315 将执行此操作。 -
非常感谢您的评论,这绝对有帮助!