首页 > 解决方案 > Pandas 生成具有值范围的数据框

问题描述

我有一个数据框:

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

我想不出办法。正确的做法是什么?

标签: pythonpandas

解决方案


用于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

推荐阅读