python - 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
我想不出办法。正确的做法是什么?
解决方案
用于product
所有组合,创建DataFrame
和merge
左连接:
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
推荐阅读
- react-native - 在使用 VSCode 在 React Native 中进行调试时,有什么方法可以特别设置 iPhone 6s?
- node.js - 如何从日志消息中调试 node.js 程序
- c++ - 如何不忽略构造函数参数之前的空格?
- tensorflow - Keras - 添加的图层必须是图层类的实例。找到:张量
- java - 如何在 Jenkins 中使用构建参数编辑 app.properties 文件
- c - c中位移和加法后的变量值不正确
- c# - 执行搜索后的网格视图排序和分页
- c++ - 使用 CMake 分发 Qt5 控制台应用程序
- c - 标记化后如何使字符串包含分隔符?
- javascript - 应该将 body.appendChild 片段(helpcrunch 聊天)添加到 Vue 单页应用程序的什么位置?