我有一个包含许多列的df。我想按id
和transform
这些列的一个子集进行分组,其余部分保持不变。最好的方法是什么?特别是,我有一个包含一堆id的df,我希望在每个id中z-score列a
和{c
应该保持不变。在我的实际问题中,我有更多的专栏。在
我能想到的最好的方法是将{col_name: function_name}
的dict
传递给transform
。出于某种原因,这会引发TypeError
。在
MWE:
import pandas as pd
import numpy as np
np.random.seed(123) #reproducible ex
df = pd.DataFrame(data = {"a": np.arange(10), "b": np.arange(10)[::-1], "c": np.random.choice(a = np.arange(10), size = 10)}, index = pd.Index(data = np.random.choice(a = [1,2,3], size = 10), name = "id"))
#create a dict for all columns other than "c" and the function to do the transform
fmap = {k: lambda x: (x - x.mean()) / x.std() for k in df.columns if k != "c"}
df.groupby("id").transform(fmap) #yields error that "dict" is unhashable
原来这是一个已知的错误:https://github.com/pandas-dev/pandas/issues/17309
一种可能的解决方案是先按
difference
过滤列名称,因为dict
还不能处理transfrom
:相关问题 更多 >
编程相关推荐