我有一个带有列表列的Pandas DataFrame,如下所示。
selection weeks
0 2 [43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
1 3 [43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
2 1 [43, 44, 45, 46, 47, 48, 49, 50, 51, 52]
我如何能够基于selection
的值获得前N个元素来获得以下结果?
selection weeks select_week
0 2 [43, 44, 45, 46, 47, 48, 49, 50, 51, 52] [43, 44]
1 3 [43, 44, 45, 46, 47, 48, 49, 50, 51, 52] [43, 44, 45]
2 1 [43, 44, 45, 46, 47, 48, 49, 50, 51, 52] [43]
答案 0 :(得分:3)
将列表理解与通过索引选择一起使用:
df['select_week'] = [x[:y] for x, y in df[['weeks','selection']].to_numpy()]
df['select_week'] = df.apply(lambda x: x['weeks'][:x['selection']], axis=1)