微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过两个Pandas Dataframe进行迭代+创建新列

如何解决通过两个Pandas Dataframe进行迭代+创建新列

我是使用Pandas的新手,我试图遍历不同Dataframe中的两列,如果两列具有相同的单词,则将“ yes”追加到另一列。如果没有,请加上“否”。

这就是我所拥有的:

    for row in df1.iterrows():
     for word in df2.iterrows():
       if df1['word1'] == df2['word2']:
         df1.column1.append('Yes') #I just want to have two columns in binary form,if one is yes the other must be no
         df2.column2.append('No')

       else:
         df1.column1.append('No')
         df2.column2.append('Yes')

我现在有:

      column1      column2  column3   
       apple        None    None
       orange       None    None
       banana       None    None
       tomato       None    None
       sugar        None    None
       grapes       None    None
       fig          None    None

我想要:

      column1      column2  column3   
       apple           Yes       No
       orange          No        No
       banana          No        No
       tomato          No        No
       sugar           No        Yes
       grapes          No        Yes
       figs            No        Yes


    Sample of words from df1: apple,orange,pear
    Sample of words from df2: yellow,green

我收到此错误只能比较标记相同的系列对象

注意:df2中的单词为2500,而df1中的单词为500。 任何帮助表示赞赏!

解决方法

我认为最好从两列中获取set个单词,然后再进行查找。这样也会更快。像这样:

words_df1 = set(df1['word1'].tolist())
words_df2 = set(df2['word2'].tolist())

然后做

df1['has_word2'] = df1['word1'].isin(words_df2)
df2['has_word1'] = df2['word2'].isin(words_df1)
,

实际上,您想填写:

  • df1.column1 具有:
    • -如果该行中的 word1 出现在 df2.word1 中(在任何行中),
    • -否则,
  • df2.column2 具有:
    • -如果该行中的 word2 出现在 df1.word2 中(在任何行中),
    • -否则。

要执行此操作,可以运行:

df1['column1'] = np.where(df1.word1.isin(df2.word2),'Yes','No')
df2['column2'] = np.where(df2.word2.isin(df1.word1),'No')

为了测试我的代码,我使用了以下数据框:

df1:                 df2:
        word1                word2
0       apple        0      yellow
1      orange        1      orange
2        pear        2       green
3  strawberry        3  strawberry
                     4        plum

我的代码的结果是:

df1:                       df2:
        word1 column1              word2 column2
0       apple      No      0      yellow      No
1      orange     Yes      1      orange     Yes
2        pear      No      2       green      No
3  strawberry     Yes      3  strawberry     Yes
                           4        plum      No

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。