根据不同列的值从熊猫列表列获取列表元素

时间:2020-11-02 06:25:21

标签: python pandas dataframe

我有一个带有列表列的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]

1 个答案:

答案 0 :(得分:3)

将列表理解与通过索引选择一起使用:

df['select_week'] = [x[:y] for x, y in df[['weeks','selection']].to_numpy()]

DataFrame.apply

df['select_week'] = df.apply(lambda x: x['weeks'][:x['selection']], axis=1)