pandas - 如何合并(使用DataFrame)具有相同输入但顺序不同的两个数据集
问题描述
我有两个数据集,其中一个本质上可以被视为描述符集,另一个包含信息。
我有一个简单的例子来说明我的意思。
import pandas as pd
第一个数据集,即描述符:
df1 = pd.DataFrame({"color": ["blue", "yellow", "red"],
"abbv": ["b", "y", "r"]})
第二个数据集:
df2 = pd.DataFrame({"color_1": ["blue", "red", "yellow"],
"color_2": ["yellow", "blue", "red"],
"total": ["green", "purple", "orange"]})
我想要做的是使用 pd.merge 来合并两个数据集,使最终的数据集看起来像这样:
| color_1 | color_2 | total | abbv_1 | abbv_2 |
| ------- | ------- | ----- | ------ | ------ |
| blue | yellow | green | b | y |
. . . . .
. . . . .
解决方案
可以使用创建映射df1
系列set_index
。然后可以添加新df2
列Series.map
:
# Create the Mapping Series
mapper = df1.set_index('color')['abbv']
# Add the New Columns
df2['abbv_1'] = df2['color_1'].map(mapper)
df2['abbv_2'] = df2['color_2'].map(mapper)
或者通过过滤列来迭代所有颜色列str.contains
:
mapper = df1.set_index('color')['abbv']
for c in df2.columns[df2.columns.str.contains('color')]:
df2[f'abbv_{c.rsplit("_", 1)[-1]}'] = df2[c].map(mapper)
df2
:
color_1 color_2 total abbv_1 abbv_2
0 blue yellow green b y
1 red blue purple r b
2 yellow red orange y r
推荐阅读
- excel - 尝试使用 MonthView 控件时的错误消息
- ruby-on-rails - 未定义的方法“protect_against_forgery?” 对于#<#
我正在努力解决,我认为这是一个简单的问题。我正在创建一个注册表单,您可以在其中创建帐户和用户(一个帐户可以有多个用户)。但是,在加载 new.html.erb 视图时,我收到以下错误:
undefined method `protect_against_forgery?' for #<#<Class:0x00>
- sql - 从非 Azure SQL 数据库恢复备份
- python - 为什么它打印两倍的“大”对角线(矩阵)
- xml - UPnP 和 SOAP 到路由器
- cygwin - Cygwin make 命令 - gcc 错误:没有这样的文件或目录
- java - 在屏幕中的不同 Fragment 之间共享一个 ViewModel 实例
- javascript - 当数组存储为全局变量时,增加数组的索引不起作用
- node.js - Async/Await:了解 Async/Await 的问题
- r - 有谁知道如何使用 ggplot 在图表上重新标记 x 和 y 轴和图例......还有一种方法可以将条形图堆叠在一起吗?