Python Pandas:使用切片作为变量的表操作 [英] Python Pandas: Table manipulation with slices as variables
问题描述
我有一张如下表(黑色).我想在右侧创建一个额外的列,例如以红色显示.基本上,对于切片"列中的每个切片变量,我都希望从低"列中检索相应的值.
I have a table such as follow (in black). I would like to create an additional column such as visible in red, to the right. Basically for each slice variable in the "slice" column, I want retrieve the corresponding values from the "low" column.
我尝试了无数种方法,我已经在这里发布了一个问题,试图解决我可能会使用的一种方法:
I have tried countless ways of doing that, I already posted a question here trying to address one of the approach i though would work:
Python Pandas:与Pandas一起使用时,该功能不起作用apply()
该问题的一位答复者建议我简单地询问如何实现它,因此我就在这里.
One of the respondents to that question suggested that i simply ask how to achieve it, hence here I am.
我还重新发布了下面的代码以重建该数据框:
I also repost below the code to reconstruct that dataframe:
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
这篇关于Python Pandas:使用切片作为变量的表操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!