【问题标题】:Compare values in two different pandas columns比较两个不同 pandas 列中的值
【发布时间】:2020-02-06 19:54:12
【问题描述】:

我有一个如下所示的数据框:

Fruit   Cost    Quantity    Fruit_Copy
Apple   0.5 6   Watermelon
Orange  0.3 2   Orange
Apple   0.5 8   Apple
Apple   0.5 7   Apple
Banana  0.25    8   Banana
Banana  0.25    7   Banana
Apple   0.5 6   Apple
Apple   0.5 3   Apple

我想在 pandas 中编写一个 sn-p,比较 Fruit 和 Fruit_Copy 并输出一个新列“Match”,指示 Fruit 中的值是否 = Fruit_Copy。

提前致谢!

【问题讨论】:

  • 不完全是,因为我希望第三列位于原始数据框中,这样我就可以轻松地隔离 match = false 的行。

标签: python-3.x pandas


【解决方案1】:

假设您的数据框是“水果”。然后你可以利用 Pandas Series Equals 函数pd.Series.eq as,

fruits['Match'] = pd.Series.eq(fruits['Fruit'],fruits['Fruit_Copy'])

【讨论】:

    【解决方案2】:

    这样的事情会起作用。

    df.loc[df['Fruit'] == df['Fruit_Copy'], 'Match'] = 'Yes'
    

    使用numpy.where:

    df['Match'] = np.where(df['Fruit'] == df['Fruit_Copy'], 'Yes', 'No')
    

    【讨论】:

      【解决方案3】:

      你可以试试这样的:

      import pandas as pd
      import numpy as np
      
      fruits = pd.DataFrame({'Fruit':['Apple', 'Orange', 'Apple', 'Apple', 'Banana', 'Banana', 'Apple', 'Apple'], 'Cost':[0.5,0.3,0.5,0.5,0.25,0.25,0.5,0.5], 'Quantity':[6,2,8,7,8,7,6,3], 'Fruit_Copy':['Watermelon', 'Orange', 'Apple', 'Apple', 'Banana', 'Banana', 'Apple', 'Apple']})
      fruits['Match'] = np.where(fruits['Fruit'] == fruits['Fruit_Copy'], 1, 0)
      fruits
      
          Fruit  Cost  Quantity  Fruit_Copy  Match
      0   Apple  0.50         6  Watermelon      0
      1  Orange  0.30         2      Orange      1
      2   Apple  0.50         8       Apple      1
      3   Apple  0.50         7       Apple      1
      4  Banana  0.25         8      Banana      1
      5  Banana  0.25         7      Banana      1
      6   Apple  0.50         6       Apple      1
      7   Apple  0.50         3       Apple      1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        • 2015-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-09
        • 1970-01-01
        相关资源
        最近更新 更多