【发布时间】:2017-10-15 20:52:25
【问题描述】:
我有两个列名不同的数据框,每个有 10 行。我要做的是比较列值,如果它们匹配,则将电子邮件地址从 df2 复制到 df1。我看过这个例子,但我的列名不同How to join (merge) data frames (inner, outer, left, right)?。我已经看到this example 以及np.where 使用了多个条件,但是当我这样做时,它给了我以下错误:
ValueError: Wrong number of items passed 2, placement implies 1
我想做的事:
我想要做的是将 df1 的第一行 2 列(first,last_huge)与 df2 列的所有行(first_small,last_small)进行比较,如果找到匹配项,则从 df2 中的特定列获取电子邮件地址并分配它到 df1 中的一个新列。任何人都可以帮我解决这个问题我只复制了下面的相关代码并且它不能完全工作只是向 new_email 添加 5 条新记录。
最初我所做的是将 df1['first'] 与 df2['first'] 进行比较
data1 = {"first":["alice", "bob", "carol"],
"last_huge":["foo", "bar", "baz"],
"street_huge": ["Jaifo Road", "Wetib Ridge", "Ucagi View"],
"city_huge": ["Egviniw", "Manbaali", "Ismazdan"],
"age_huge": ["23", "30", "36"],
"state_huge": ["MA", "LA", "CA"],
"zip_huge": ["89899", "78788", "58999"]}
df1 = pd.DataFrame(data1)
data2 = {"first_small":["alice", "bob", "carol"],
"last_small":["foo", "bar", "baz"],
"street_small": ["Jsdffo Road", "sdf Ridge", "sdfff View"],
"city_huge": ["paris", "london", "rome"],
"age_huge": ["28", "40", "56"],
"state_huge": ["GA", "EA", "BA"],
"zip_huge": ["89859", "78728", "56999"],
"email_small":["alice@xyz.com", "bob@abc.com", "carol@jkl.com"],
"dob": ["31051989", "31051980", "31051981"],
"country": ["UK", "US", "IT"],
"company": ["microsoft", "apple", "google"],
"source": ["bing", "yahoo", "google"]}
df2 = pd.DataFrame(data2)
df1['new_email'] = np.where((df1[['first']] == df2[['first_small']]), df2[['email_small']], np.nan)
现在只向 new_email 添加 5 条记录,其余为 nan。并向我显示此错误:
ValueError: Can only compare identically-labeled Series objects
【问题讨论】:
-
当您可以在线提供具有代表性的示例数据时,请不要发布数据截图。它使其他人更容易帮助您。
-
好的,我会解决的