gpt4 book ai didi

python - 如何从 Pandas 中的另一列扩展范围的数据表

转载 作者:行者123 更新时间:2023-11-28 20:00:33 27 4
gpt4 key购买 nike

我有以下数据表

import pandas as pd
dt = pd.DataFrame({'id_audience': ['Female 13-17', 'Female 18-20'],
'gender': ['female', 'female'],
'age_min': [13, 18],
'age_max': [17, 20]})

我想扩展这个数据框,有一个额外的列(age),age 应该是 age_minage_max

最终结果是这样的:

 dt = pd.DataFrame({'id_audience': ['Female 13-17', 'Female 13-17', 'Female 13-17', 'Female 13-17',
'Female 13-17', 'Female 18-20', 'Female 18-20', 'Female 18-20', ],
'gender': ['female', 'female', 'female', 'female', 'female', 'female', 'female', 'female'],
'age_min': [13, 13, 13, 13, 18, 18, 18, 18],
'age_max': [17, 17, 17, 17, 20, 20, 20, 20],
'age': [13, 14, 15, 16, 17, 18, 19, 20]})

有什么想法吗?

最佳答案

也像@Wen一样使用explode,但是在最小/最大年龄列上直接访问范围


dt.assign(
age=[np.arange(x, y+1) for x, y in zip(dt['age_min'], dt['age_max'])]
).explode('age').reset_index(drop=True)

    id_audience  gender  age_min  age_max age
0 Female 13-17 female 13 17 13
1 Female 13-17 female 13 17 14
2 Female 13-17 female 13 17 15
3 Female 13-17 female 13 17 16
4 Female 13-17 female 13 17 17
5 Female 18-20 female 18 20 18
6 Female 18-20 female 18 20 19
7 Female 18-20 female 18 20 20

关于python - 如何从 Pandas 中的另一列扩展范围的数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57359723/

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