下面是我正在比较的两个数据框。当我能够匹配列Usage
时,我想在df2
的列Item
下获得相应的列值。感谢帮助。
df1 = pd.DataFrame({ 'Number':[1.0,3.0,4.0,5.0,8.0,12.0,32.0,58.0,72.0] , 'Item': ['Phone', 'Watch', 'Pen', 'Pencil', 'Pencil', 'toolkit', 'box', 'fork', 'toy']})
df2 = pd.DataFrame({'Number':[3.0, 4.0, 8.0, 12.0, 15.0, 32.0, 54.0, 58.0, 72.0], 'Item':['Watch', 'Pen', 'Pencil', 'Eraser', 'bottle', 'box', 'toolkit', 'fork', 'Phone'], 'Usage':['Time', 'Writing', 'Writing', 'Cleaning', 'Water', 'storage', 'Utility', 'Eat', 'Communication']})
df1
Number Item
0 1.0 Phone
1 3.0 Watch
2 4.0 Pen
3 5.0 Pencil
4 8.0 Pencil
5 12.0 toolkit
6 32.0 box
7 58.0 fork
8 72.0 toy
df2
Number Item Usage
0 3.0 Watch Time
1 4.0 Pen Writing
2 8.0 Pencil Writing
3 12.0 Eraser Cleaning
4 15.0 bottle Water
5 32.0 box storage
6 54.0 toolkit Utility
7 58.0 fork Eat
8 72.0 Phone Communication
用于匹配的代码如下。即使只有数字匹配,它也会显示“ MatchedBoth”。这需要解决。
import numpy as np
df3 = df1.copy()
df3['Matching'] = np.nan
df3.loc[(df3.Number.isin(df2.Number)) & (df3.Item.isin(df2.Item)), 'Matching'] = 'MatchedBoth'
df3.loc[(df3.Number.isin(df2.Number)) & (~df3.Item.isin(df2.Item)),'Matching'] = 'Matched Number Only'
df3.Matching.fillna('No Match', inplace=True)
在同一代码中,有可能嵌入一个返回值,该返回值可以从Usage
获取df2
列值,每个匹配行对应。在某些情况下,可能有多个行可以匹配,因此我们可能需要将相应的Usage
列值放入列表或最终输出中类似的内容。
注意:在我的实际数据框中,我除此以外还有几列,因此,如果使用合并,则会导致巨大的数据框。我只想创建一个新列,并在df2的Usage
列中找到对应的匹配值列表。
输出应如下所示。
df3
Number Item Matching Usage
0 1.0 Phone No Match NaN
1 3.0 Watch MatchedBoth Time
2 4.0 Pen MatchedBoth Writing
3 5.0 Pencil No Match NaN
4 8.0 Pencil MatchedBoth Writing
5 12.0 toolkit Matched Number Only Utility
6 32.0 box MatchedBoth storage
7 58.0 fork MatchedBoth Eat
8 72.0 toy Matched Number Only Play
答案 0 :(得分:0)
您可以尝试这样的事情:
df3 = df1.merge(df2, on='Number', how='left')
df3['Matching'] = np.where(df3.Productdetailed == df3.Item, 'Matched', 'No Match')
df3.drop('Productdetailed', axis=1, inplace=True)
这将返回您在问题中指示的输出。
澄清后进行编辑:
def find_match(row):
if (row.Number in df2.Number.values) & (row.Item in df2.Item.values):
return "MatchedBoth"
elif ((row.Number in df2.Number.values) & ~(row.Item in df2.Item.values)):
return "Matched Number Only"
else:
return "No Match"
df3['Matching'] = df3.apply(find_match, axis=1)
df3['Usage'] = df3.Item.map(df2.set_index('Item').Usage)