python - 根据列中的字符串合并 DataFrames 列表,然后将其转换为字典
问题描述
任务描述
我想基于列(国家/地区)中的字符串合并 DataFrame 列表,然后将其转换为字典,并将 Country 列作为键,合并后的 DataFrame 作为值。数据示例:
国名列表
country_names = ['ITA', USA', 'UK', 'ARG']
命名的 DataFrame 列表df_countries
df_countries[0]
index Date A B C Country
1 2019-12-31 x y z ITA
2 2019-12-30 x y z ITA
df_countries[1]
index Date A B C Country
1 2019-12-31 x y z ITA
2 2019-12-30 x y z ITA
df_countries[2]
index Date A B C Country
1 2019-12-31 x y z USA
2 2019-12-30 x y z USA
df_countries[3]
index Date A B C Country
1 2019-12-31 x y z ARG
2 2019-12-30 x y z ARG
例如,我希望 ITA 在合并后看起来像下面这样,然后以 ITA 作为键等创建一个字典:
index Date A B C Country
1 2019-12-31 x y z ITA
2 2019-12-30 x y z ITA
3 2019-12-31 x y z ITA
4 2019-12-30 x y z ITA
任何帮助都会很棒!
解决方案
从我的评论中进行了一些详细说明:您可以首先将所有数据框与 合并pd.concat()
,然后选择匹配的行并从中创建新的数据框:
merged_frame = pd.concat(df_countries)
country_dict = {}
for country in country_names:
country_dict[country] = merged_frame[merged_frame['Country'] == country]
您也可以选择调用country_dict[country].reset_index()
来修复新帧的索引。
推荐阅读
- python - ctypes:如何为引用自身的 C 结构定义 ctypes.Structure?
- javascript - 在不使用 Map 的情况下通过键映射 Typescript 枚举?
- java - 如何阻止电子邮件通讯弹出窗口拦截点击?
- android - Android NDK - C++ 异常导致第 3 方本机库崩溃
- d3.js - 获取数组中对象的平均值
- javascript - React Native:在上下文之间共享状态、api调用响应
- javascript - 带有 Promise 和 Proxyquire 的单元测试对象方法
- python - 查找列表元素的一部分
- android - Android - 如何提取/备份您的手机联系人列表和浏览器书签(股票浏览器,而不是 chrome)
- jquery - Rails 6 Jquery 错误:未捕获的 TypeError:$(...).closest(...).transition 不是函数