gpt4 book ai didi

python - 如何根据数组索引从 Pandas 组内的相对索引中选择值

转载 作者:行者123 更新时间:2023-12-03 20:00:54 26 4
gpt4 key购买 nike

我有一个 DataFrame,它已经按列排序 ('year', 'month') ,看起来像这样:

df = pd.DataFrame({
'year': [2020, 2020, 2020, 2021, 2021, 2021, 2021],
'month': [1, 2, 5, 2, 4, 7, 9],
'values': [
['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'],
['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'D']
]
})

print(df)

year month values
0 2020 1 ['a', 'b', 'c']
1 2020 2 ['a', 'b', 'c']
2 2020 5 ['a', 'b', 'c']
3 2021 2 ['A', 'B', 'C', 'D']
4 2021 4 ['A', 'B', 'C', 'D']
5 2021 7 ['A', 'B', 'C', 'D']
6 2021 9 ['A', 'B', 'C', 'D']
我想创建一个名为 'value' 的新列,其中包含 'values' 上第 i 个元素的值数组,其中 i 是相应月份的索引,按年份分组。在这种情况下,结果将是:
    year    month   values                  value
0 2020 1 ['a', 'b', 'c'] 'a'
1 2020 2 ['a', 'b', 'c'] 'b'
2 2020 5 ['a', 'b', 'c'] 'c'
3 2021 2 ['A', 'B', 'C', 'D'] 'A'
4 2021 4 ['A', 'B', 'C', 'D'] 'B'
5 2021 7 ['A', 'B', 'C', 'D'] 'C'
6 2021 9 ['A', 'B', 'C', 'D'] 'D'

我假设阵列上没有丢失数据。我尝试过的一些行涉及使用 .groupby('year')其次是 .get_loc('month') ,但到目前为止无法得到正确的结果。
编辑:
有一个细节我忘了说:月份不一定在一个统一的范围内,因此指数并不总是 month-1 .我已经编辑了有问题的 DataFrame 以反射(reflect)这种细微差别。

最佳答案

理解

df.assign(value=[v[m-1] for v, m in zip(df['values'], df['month'])])

year month values value
0 2020 1 [a, b, c] a
1 2020 2 [a, b, c] b
2 2020 3 [a, b, c] c
3 2021 1 [A, B, C, D] A
4 2021 2 [A, B, C, D] B
5 2021 3 [A, B, C, D] C
6 2021 4 [A, B, C, D] D

替代 maplist.__getitem__
df.assign(value=[*map(list.__getitem__, df['values'], df['month'] - 1)])

关于python - 如何根据数组索引从 Pandas 组内的相对索引中选择值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66695966/

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