【发布时间】:2021-10-08 11:26:16
【问题描述】:
我的问题如下:我有两个长度不同的数据框。两者都有共同的“标题”列,看起来像这样:
df1:
idn title ISBN other_stuff
343 some title 3847832342 ahfsdfasjdfs
351 other title 9785482733 asfdjkajskfdfd
df2:
idn title ISBN important other_stuff
444 some title 633847347 interesting dakjsfdlfeihaiwfh
566 some title 242343243 4wkhashfuihwauehfa
545 further title 543545455 r3434
我想要查看第一个数据帧 (df1) 中的“标题”列,并检查第二个数据帧 (df2) 中的“标题”列。如果它们匹配(如“某个标题”的情况,那么我想向 df1 添加一列,其中包含 df2 中“重要”列中的值。
我现在尝试了以下方法:
df1['new_column'] = np.where(df1['title'] != df2['title'], df2['important'], 'N/A')
但我收到一条错误消息:
ValueError: Can only compare identically-labeled Series objects
到目前为止,我已经尝试重置两个数据帧的索引以及删除它们,但这并没有帮助。我不知道如何解决这个问题以及为什么会发生这种情况 - 也许问题是我在 df2 中有两个“标题”命中?如果是这样,我该如何解决这个问题?我很乐意只使用“重要”条目中的第一个命中,然后忽略“某个标题”的所有其他命中,但不知道该怎么做 - 如果可能的话?
【问题讨论】:
标签: python pandas dataframe conditional-statements