gpt4 book ai didi

python - Pandas 生成具有值范围的数据框

转载 作者:太空宇宙 更新时间:2023-11-04 02:07:37 26 4
gpt4 key购买 nike

我有一个数据框:

speciality_id   speciality_name
1 Acupuncturist
2 Andrologist
3 Anaesthesiologist
4 Audiologist
5 Ayurvedic Doctor
6 Biochemist
7 Biophysicist

我想复制上述数据框的值范围、年份和月份。

例如:

year = [2018]
Month = [1,2]

我想生成如下数据框:

Year    Month   speciality_id   speciality_name
2018 1 1 Acupuncturist
2018 1 2 Andrologist
2018 1 3 Anaesthesiologist
2018 1 4 Audiologist
2018 1 5 Ayurvedic Doctor
2018 1 6 Biochemist
2018 1 7 Biophysicist

2018 2 1 Acupuncturist
2018 2 2 Andrologist
2018 2 3 Anaesthesiologist
2018 2 4 Audiologist
2018 2 5 Ayurvedic Doctor
2018 2 6 Biochemist
2018 2 7 Biophysicist

我想不出一个方法。正确的做法是什么?

最佳答案

对所有组合使用product,创建DataFramemerge左连接:

year = [2018]
Month = [1,2]

from itertools import product

df1 = pd.DataFrame(list(product(year, Month, df['speciality_id'])),
columns=['Year','Month','speciality_id'])
print (df1)
Year Month speciality_id
0 2018 1 1
1 2018 1 2
2 2018 1 3
3 2018 1 4
4 2018 1 5
5 2018 1 6
6 2018 1 7
7 2018 2 1
8 2018 2 2
9 2018 2 3
10 2018 2 4
11 2018 2 5
12 2018 2 6
13 2018 2 7

df = df1.merge(df, on='speciality_id', how='left')
print (df)
Year Month speciality_id speciality_name
0 2018 1 1 Acupuncturist
1 2018 1 2 Andrologist
2 2018 1 3 Anaesthesiologist
3 2018 1 4 Audiologist
4 2018 1 5 Ayurvedic Doctor
5 2018 1 6 Biochemist
6 2018 1 7 Biophysicist
7 2018 2 1 Acupuncturist
8 2018 2 2 Andrologist
9 2018 2 3 Anaesthesiologist
10 2018 2 4 Audiologist
11 2018 2 5 Ayurvedic Doctor
12 2018 2 6 Biochemist
13 2018 2 7 Biophysicist

关于python - Pandas 生成具有值范围的数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54307175/

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