【发布时间】:2021-03-18 17:16:45
【问题描述】:
我有一个 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-th 元素的值,其中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 以反映这种细微差别。
【问题讨论】:
-
根据您的编辑查看我对答案的编辑,即索引并不总是
month-1。 -
也根据数据样本变化进行了编辑。