gpt4 book ai didi

Python Pandas : Table manipulation with slices as variables

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

我有一个表格,例如follow(黑色)。我想创建一个附加列,例如右侧可见的红色列。基本上,对于“切片”列中的每个切片变量,我想从“低”列中检索相应的值。

enter image description here

我已经尝试了无数种方法来做到这一点,我已经在这里发布了一个问题,试图解决我认为可行的方法之一:

Python Pandas: Function doesn't work when used with apply()

该问题的一位受访者建议我只是问如何实现它,因此我在这里。

我还在下面重新发布了重建该数据帧的代码:

df = pd.DataFrame(dict, columns=["low", "slices"])

{'low': {0: 1207.25,
1: 1207.5,
2: 1205.75,
3: 1206.0,
4: 1201.0,
5: 1202.75,
6: 1203.75},
'slices': {0: [slice(1, 1, None)],
1: [slice(1, 2, None), slice(2, 2, None)],
2: [slice(1, 3, None), slice(2, 3, None), slice(3, 3, None)],
3: [slice(1, 4, None),
slice(2, 4, None),
slice(3, 4, None),
slice(4, 4, None)],
4: [slice(1, 5, None),
slice(2, 5, None),
slice(3, 5, None),
slice(4, 5, None),
slice(5, 5, None)],
5: [slice(1, 6, None),
slice(2, 6, None),
slice(3, 6, None),
slice(4, 6, None),
slice(5, 6, None),
slice(6, 6, None)],
6: [slice(1, 7, None),
slice(2, 7, None),
slice(3, 7, None),
slice(4, 7, None),
slice(5, 7, None),
slice(6, 7, None),
slice(7, 7, None)]}}

最佳答案

这样定义你的函数

def fun(slices):
return [df.low.loc[s].tolist() for s in slices]

并应用于切片列

df['slices_low'] = df.slices.apply(fun)

df

enter image description here

关于Python Pandas : Table manipulation with slices as variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41454751/

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