python - 解压数据框字典并将键设置为列值
问题描述
我有以下数据框字典(df):
([('Austria',
Name Value
0 3 BG EMCore Convertibles Global CHF R T 5
1 3 BG EMCore Convertibles Global R T 6
[2 rows x 2 columns]),
('Belgium',
Name Value
0 AG Life Alternative Investments 7
1 AG Life Balanced 1
2 AG Life Bonds Global 2
3 AG Life Bonds Indexed 7
[4 rows x 2 columns])])
我想将数据转换为单个数据框,同时将关键字符串设置为附加列
我首先将字典转换为数据框列表:
mylist=[i[1] for i in df.items()]
然后我可以通过以下方式将数据框合并为一个数据框:
master_frame=pd.concat(mylist, sort=True)
但我想将字典中的键设置为附加列
如果是这样的预期结果:
Name Value Country
0 3 BG EMCore Convertibles Global CHF R T 5 Austria
1 3 BG EMCore Convertibles Global R T 6 Austria
2 AG Life Alternative Investments 7 Belgium
3 AG Life Balanced 1 Belgium
4 AG Life Bonds Global 2 Belgium
5 AG Life Bonds Indexed 7 Belgium
提前致谢
解决方案
对于一个dict
喜欢:
dfs = {'Austria': AustriaDF, 'Belgium': BelgiumDF}
您可以根据键添加新列,然后将它们连接起来:
for country, df in dfs.items():
df['Country'] = country
master_frame = pd.concat(sorted(dfs.values(), key=lambda df: df['Country'][0]), ignore_index=True)
价值master_frame
:
Name Value Country
0 3 BG EMCore Convertibles Global CHF R T 5 Austria
1 3 BG EMCore Convertibles Global R T 6 Austria
2 AG Life Alternative Investments 7 Belgium
3 AG Life Balanced 1 Belgium
4 AG Life Bonds Global 2 Belgium
5 AG Life Bonds Indexed 7 Belgium
推荐阅读
- matlab - LSTM 中的 NumHiddenUnits
- javascript - 将组件的方法引用传递给 Vuex 中的操作
- python - 尝试在非包中进行相对导入”,即使使用 __init__.py
- azure-active-directory - Azure AD - 当用户确实有会话时,openid 连接 post_logout_redirect_uri
- reactjs - 在 ReactJS 中使用 Context 时如何将单个道具值传递给同一个组件
- xml - 按子节点内容对 XML 进行排序
- python-3.x - python中的ANOVA特征选择
- python - 如何在异常发生后立即停止执行函数?[Python]
- bash - 通过 STDIN 发送脚本和文件内容
- git - 无法删除具有特殊字符的 Git 标签