【发布时间】:2017-02-10 12:23:50
【问题描述】:
我有一个df,其中包含我的主要数据,其中有一百万个rows。我的主要数据也有30个columns。现在我想在我的df 中添加另一列,名为category。 category 是 df2 中的 column,其中包含大约 700 个 rows 和另外两个 columns,它们将与 df 中的两个 columns 匹配。
我首先在df2 和df 中设置一个index,它将在帧之间匹配,但是df2 中的一些index 在df 中不存在。
df2 中的其余列称为AUTHOR_NAME 和CATEGORY。
df 中的相关列称为AUTHOR_NAME。
df 中的某些AUTHOR_NAME 在df2 中不存在,反之亦然。
我想要的指令是:当df中的index匹配df2中的index和df中的title匹配df2中的title时,将category添加到@ 987654356@,否则在category中添加NaN。
示例数据:
df2
AUTHOR_NAME CATEGORY
Index
Pub1 author1 main
Pub2 author1 main
Pub3 author1 main
Pub1 author2 sub
Pub3 author2 sub
Pub2 author4 sub
df
AUTHOR_NAME ...n amount of other columns
Index
Pub1 author1
Pub2 author1
Pub1 author2
Pub1 author3
Pub2 author4
expected_result
AUTHOR_NAME CATEGORY ...n amount of other columns
Index
Pub1 author1 main
Pub2 author1 main
Pub1 author2 sub
Pub1 author3 NaN
Pub2 author4 sub
如果我使用df2.merge(df,left_index=True,right_index=True,how='left', on=['AUTHOR_NAME']),我的df 会比预期的大三倍。
所以我认为合并可能是解决此问题的错误方法。我真正想做的是使用df2 作为查找表,然后根据是否满足某些条件将type 值返回到df。
def calculate_category(df2, d):
category_row = df2[(df2["Index"] == d["Index"]) & (df2["AUTHOR_NAME"] == d["AUTHOR_NAME"])]
return str(category_row['CATEGORY'].iat[0])
df.apply(lambda d: calculate_category(df2, d), axis=1)
但是,这会引发一个错误:
IndexError: ('index out of bounds', u'occurred at index 7614')
【问题讨论】:
-
我不确定
on和left_index/right_index是否一起工作。也许你需要on=['Index', 'AUTHOR_NAME'](或类似的东西)。而且我不确定df2.merge(df,...)中留下了哪个数据框。也许你需要how="right"或pd.merge(left=df, right=df2, ...)
标签: python pandas merge populate