vae*_*vae 5 python transform pandas
我在使用 Pandas .groupby()和.transform() 时遇到了一个奇怪的行为。下面是生成数据集的代码:
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"]})
Run Code Online (Sandbox Code Playgroud)
这是我为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
Run Code Online (Sandbox Code Playgroud)
然后我将我的函数与转换一起使用 - 完美无缺并得到我想要的。
df_2 = stack.groupby(["City"])['Name','Random_Number'].transform(some)
Run Code Online (Sandbox Code Playgroud)
然而,奇怪的事情发生了,当我从切换山坳的顺序['Name','Random_Number']来['Random_Number','Name']
df_2 = stack.groupby(["City"])['Random_Number','Name'].transform(some)
Run Code Online (Sandbox Code Playgroud)
当您查看'Name'列中的单元格时,pandas 似乎将所有内容多次放入一个单元格中:
df_2.iloc[0,1]
# Return:
# 0 Alice--4
# 1 Bob--4
# 3 Mallory--4
# 4 Bob--4
# Name: Name, dtype: object
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
问题出在你的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
Run Code Online (Sandbox Code Playgroud)