【发布时间】:2019-06-06 11:26:31
【问题描述】:
我想用df2 数据框的“类别”列中的正确值填充df1 数据框的“类别”列。
import pandas as pd
df1 = pd.DataFrame({"Receiver": ["Insurance company", "Shop", "Pizza place", "Library", "Gas station 24/7", "Something else", "Whatever receiver"], "Category": ["","","","","","",""]})
df2 = pd.DataFrame({"Category": ["Insurances", "Groceries", "Groceries", "Fastfood", "Fastfood", "Car"], "Searchterm": ["Insurance", "Shop", "Market", "Pizza", "Burger", "Gas"]})
输出:
df1
Receiver Category
0 Insurance company
1 Shop
2 Pizza place
3 Library
4 Gas station 24/7
5 Something else
6 Whatever receiver
df2
Category Searchterm
0 Insurances Insur
1 Groceries Shop
2 Groceries Market
3 Fastfood Pizza
4 Fastfood Burger
5 Car Gas
我想逐行比较df1["Receiver"] 和df2["Searchterm"],如果后者甚至部分匹配前者,则将该行的df2["Category"] 分配给df1["Category"]。
例如,df2["Searchterm"] 中的“Pizza”部分匹配 df1["Receiver"] 中的“Pizza place”,所以我想将“Fastfood”(这是 df2["Category"] 中的 Pizza 类别)分配给“Pizza place” df1["Category"] 中的类别。
期望的输出是:
df1
Receiver Category
0 Insurance company Insurances
1 Shop Groceries
2 Pizza place Fastfood
3 Library
4 Gas station 24/7 Car
5 Something else
6 Whatever receiver
那么我怎样才能用正确的类别填写df1["Category"]?谢谢。
【问题讨论】:
标签: python pandas dataframe string-matching