gpt4 book ai didi

python - 在 groupby 之后展开由 lambda 函数创建的列表

转载 作者:行者123 更新时间:2023-12-01 09:25:00 24 4
gpt4 key购买 nike

我在按索引对数据帧进行分组后应用 lambda 函数。此函数将两个元素添加到原始组中。

df.groupby(df.index).apply(lambda x: fun(x.col))    

函数所在位置:

def fun(x):
return np.r_[np.repeat(x[:1],2),x,np.repeat(x[:-1],2)]

但是它会返回每个组的列表,

33    [0.9526133823707408, 0.9526133823707408, 0.952...
14 [0.7399641356312007, 0.7399641356312007, 0.739...
16 [0.9932682467249898, 0.9932682467249898, 0.993...
40 [0.8378176113760183, 0.8378176113760183, 0.837...

如何展开这些列表,以便列表中的每个元素都显示为一个新行及其相应的索引? (就和df原来的结构一样)

我尝试添加一个 .apply(pd.Series) 但它会将每个元素展开到一个新列中)。

原始结构:

33    0.952613
33 0.929144
33 0.903109
33 0.876384
33 0.850252
33 1.185296
33 1.155291
33 1.119522
...

最佳答案

使用Series作为每个numpy数组的行:

def fun(x):
return pd.Series(np.r_[np.repeat(x[:1],2),x,np.repeat(x[:-1],2)])

df = df.groupby(df.index).apply(lambda x: fun(x.col))
print (df)
0 1 2 ... 21 22 23
33 0.952613 0.952613 0.952613 ... 1.185296 1.155291 1.155291

[1 rows x 24 columns]

关于python - 在 groupby 之后展开由 lambda 函数创建的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50504409/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com