在Python中将VLOOKUP与合并一起使用

时间:2019-07-31 05:54:10

标签: python pandas

我有这个熊猫数据框,几乎有540000行:

df1.head()

    username  hour    totalCount
0   lowi      00:00   12
1   klark     00:00   0
2   sturi     00:00   2
3   nukr      00:00   10
4   irore     00:00   2

我还有另一个熊猫DataFrame,它具有近52000行和一些重复的行:

df2.head()

   username   community
0    klark       0
1    irore       2
2    sturi       2
3    sturi       2
4    sturi       2

我想将df2的'community'列合并到df1,但要根据用户名在相应的行中合并。 我使用了以下代码:

df_merge = df_hu.merge(df_comm, on='username')
df_merge

但是我得到了以下具有大约1205880行和重复行的DataFrame:

    username    hour    totalCount  community
0   lowi        00:00   12          2
1   lowi        00:00   12          2
2   lowi        00:00   12          2
3   lowi        01:00   9           2
4   lowi        01:00   9           2

预期输出为:

df_merge.head()

    username  hour    totalCount community
0   lowi      00:00   12         2
1   klark     00:00   0          0
2   sturi     00:00   2          2
3   nukr      00:00   10         1 (not showed in the example)
4   irore     00:00   2          1 (not showed in the example)

1 个答案:

答案 0 :(得分:2)

使用pandas.Series.map

df2 = df2.drop_duplicates().set_index('username')
df1['community'] = df1['username'].map(df2['community'])
print(df1)

输出:

  username   hour  totalCount  community
0     lowi  00:00          12        NaN
1    klark  00:00           0        0.0
2    sturi  00:00           2        2.0
3     nukr  00:00          10        NaN
4    irore  00:00           2        2.0

请注意,示例中的lowinukr不是df2