【问题标题】:Set values in Pandas one dataframe based on rows in second dataframe根据第二个数据帧中的行在 Pandas 一个数据帧中设置值
【发布时间】:2020-10-01 16:06:45
【问题描述】:

我有两个数据框 df1 和 df2,我想在 df1 中创建一个新列并将该列中的值设置为 0,其中 df1 中的行包含在 df2 中。更具体地说:

sample_data_1 = {'col1': ['80', '8080'], 'col2': ['0.0.0.0', '143.21.7.165']}
df1 = pd.DataFrame(data=sample_data_1)

sample_data_2 = {'col1': ['80', '8080', '1', '8888'], 'col2': ['0.0.0.0', '143.21.7.165', '1', '5.5.5.5'], 'col3': ['1','2','3']}
df2 = pd.DataFrame(data=sample_data_2)



     col1          col2
0    80         0.0.0.0
1  8080    143.21.7.165

   col1          col2 col3
0    80       0.0.0.0    1
1  8080  143.21.7.165    2
2     1             1    3
3  8888       5.5.5.5    4

我想向 df1 添加一列并将这些值设置为 0,其中 df1 中的 col1 和 col2 与 df2 中的 col1 和 col2 匹配。生成的数据框应如下所示:

    col1          col2    score
0    80         0.0.0.0   0
1  8080    143.21.7.165   0

当数据框大小相同时,我可以使用 .loc 函数和逻辑与进行直接比较,但是当它们具有不同的形状时,我会出现“无法比较系列”的异常。想法?

感谢您的帮助!

【问题讨论】:

    标签: python python-3.x pandas dataframe


    【解决方案1】:

    你可以使用df.merge:

    In [2735]: df1 = df1.merge(df2, on=['col1','col2']).drop('col3',1).assign(score=0)
    
    In [2737]: df1 
    Out[2737]: 
       col1          col2  score
    0    80       0.0.0.0      0
    1  8080  143.21.7.165      0
    

    【讨论】:

      【解决方案2】:

      如果 col1 中的条目不相同,您可以将 col1 设置为索引。 准确地说:

      df = df2.set_index('col1').reindex(df1.set_index('col1').index)
      df['score']=0
      df.reset_index(inplace=True)
      

      【讨论】:

        【解决方案3】:

        通过压缩df1, df2 中的公共列来检查成员资格这将返回布尔值

        使用np.where(condition, if condition, not condition),计算你想要的输出

        import numpy as np
        
        df1['score']=np.where([x in y for x,y in zip(df1.col1,df2.col1)],0,'not available')
        
            col1     col2          score
        0   80      0.0.0.0         0
        1   8080    143.21.7.165    0
        

        【讨论】:

          猜你喜欢
          • 2020-06-22
          • 2012-08-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-29
          • 2021-04-26
          相关资源
          最近更新 更多