python - 如何在具有相似值(但不相同)的公共列上合并 pandas 中的两个数据框?
问题描述
我正在尝试将 pandas 中的两个数据框合并到一个显示地理区域名称的公共列上。该列具有相似的值但不相同。例如,一个 DataFrame 中的值是London
,而另一个是London / Greater London
- 它们被视为不同的值,但在合并时应被视为相同的值。
In[1]:
import pandas as pd
df1 = pd.DataFrame([['London', 2], ['Bristol', 3], ['Liverpool', 6]], columns=['Area', 'B'])
df2 = pd.DataFrame([['London / Greater London', 7], ['Bristol_', 9], ['Liverpool / Liverpool', 1]], columns=['Area', 'B'])
df_merged = pd.merge(df1, df2, on="Area", indicator=True, how='outer')
df_merged
Out[1]:
Area B_x B_y _merge
0 London 2.0 NaN left_only
1 Bristol 3.0 NaN left_only
2 Liverpool 6.0 NaN left_only
3 London / Greater London NaN 7.0 right_only
4 Bristol_ NaN 9.0 right_only
5 Liverpool / Liverpool NaN 1.0 right_only
理想的输出如下所示:
Out[1]:
Area B_x B_y _merge
0 London 2.0 7.0 both
1 Bristol 3.0 9.0 both
2 Liverpool 6.0 1.0 both
有没有办法根据值的一定程度的相似性合并这两个数据框,以便将London
值London / Greater London
视为相同的值?谢谢!
解决方案
您可以首先创建两个arrays
包含重叠Area
和City
使用的索引np.where()
。我用 alist comprehension
检查每个City
是否存在并保存索引in
的列表。Areas
注意:这仅适用于string
an 的Area
包含City
string
. (即London
仅London / Greater London
当 thisarea
包含单词London
.
编码:
# Alter the column names B (present in both dfs to B_x and B_y )
df1 = pd.DataFrame([['London', 2], ['Bristol', 3], ['Liverpool', 6]], columns=['Area', 'B_x'])
df2 = pd.DataFrame([['London / Greater London', 7], ['Bristol_', 9], ['Liverpool / Liverpool', 1]], columns=['Area', 'B_y'])
# Create indices of matching string patterns
i, j = np.where([[city in area for area in df2['Area'].values] for city in df1['Area'].values])
# Create new dataframe with found indices
pd.DataFrame(np.column_stack([df1.iloc[i], df2.iloc[j]]), columns=df1.columns.append(df2.columns))
结果
Area B_x Area B_y
0 London 2 London / Greater London 7
1 Bristol 3 Bristol_ 9
2 Liverpool 6 Liverpool / Liverpool 1
推荐阅读
- python - Python ssl 无法使用 TLS1.2 客户端连接到 TLS1.2 服务器
- c# - 如何通过引号和逗号开头或结尾的引号进行解析?
- c++ - “ActivationsSource”不是类或命名空间名称
- excel - 在列中的数据更改后插入空白行
- mysql - 更改列值取决于出现次数
- python - 使用 Google Compute Engine 默认服务帐号签署 Google Cloud Storage URL
- c# - Unity 网络管理器不会在网络起始位置生成对象
- go - 对 gqlgen GraphQL API 的 curl POST 请求的正确形状是什么?
- swift - 在 Swift 中过滤 ManagedObject FetchResults 数组
- python - 如何在字典python列表中设置默认值?