【问题标题】:How to iterate through pandas columns and rows simultaneously?如何同时遍历 pandas 的列和行?
【发布时间】:2019-08-28 16:58:09
【问题描述】:

我有两个 df A 和 B,我想遍历 df B 的某些列并检查其所有行的值,看看值是否存在于 A 中的一列中,并将空值与 A 的其他列一起使用价值观。

df A:

 country region product
 USA     NY     apple
 USA     NY     orange
 UK      LON    banana
 UK      LON    chocolate
 CANADA  TOR    syrup 
 CANADA  TOR    fish

df B:

 country ID    product1     product2     product3     product4     region 
 USA     123   other stuff  other stuff  apple        NA           NA
 USA     456   orange       other stuff  other stuff  NA           NA
 UK      234   banana       other stuff  other stuff  NA           NA
 UK      766   other stuff  other stuff  chocolate    NA           NA
 CANADA  877   other stuff  other stuff  syrup        NA           NA
 CANADA  109   NA           fish         NA           other stuff  NA

所以我想遍历 dfB,例如查看 dfA.product (apple) 是否在 dfB.product1-product4 的列中,如果如 dfB 的第一行所示为真,那么我想要将 dfA.region 中的 region 值添加到 dfB 的 region 中,该值现在为 NA。

这是我的代码,我不确定它是否正确:

import pandas as pd 
from tqdm import tqdm


def fill_null_value(dfA, dfB):
    for i, row in tqdm(dfA.iterrows()):
        for index, row in tqdm(dfB.iterrows()):
            if dfB['product1'][index] == dfA['product'][i]:
                dfB['region'] =  dfA['region '][i]

            elif dfB['product2'][index] == dfA['product'[i]:
                dfB['region'] =  dfA['region'][i]

            elif dfB['product3'][index] == dfA['product'][i]:
                dfB['region'] =  dfA['region'][i]

            elif dfB['product4'][index] == dfA['product'][i]:
                dfB['region'] =  dfA['region'][i]

            else:
                dfB['region '] = "not found"


    print('outputing data')
    return dfB.to_excel('test.xlsx')

【问题讨论】:

  • 您如何区分要查找的产品值(例如apple)和不想查找的产品值(在您的示例中为other stuff)?
  • 所以我首先遍历 dfA,并使用“==”查看 apple 是否在 dfB 的每一列中。如果该值不存在,则函数不执行任何操作,但如果它将 region 值从 dfA 添加到 dfB。
  • 好吧,我明白了。我要问的是您是如何生成数据的,这样您就知道apple 是您想要查找的产品,而您显然在同一行中有其他产品但您忽略了。

标签: python pandas dataframe


【解决方案1】:

如果我在你那里我会创建一些join 然后concat 他们和drop duplicates

df_1 = df_A.merge(df_B, right_on=['country', 'product'], left_on=['country', 'product1'], how='right')
df_2 = df_A.merge(df_B, right_on=['country', 'product'], left_on=['country', 'product2'], how='right')
df_3 = df_A.merge(df_B, right_on=['country', 'product'], left_on=['country', 'product3'], how='right')
df_4 = df_A.merge(df_B, right_on=['country', 'product'], left_on=['country', 'product4'], how='right')

df = pd.concat([df_1, df_2, df_3, df_4]).drop_duplicates()

【讨论】:

    【解决方案2】:

    这里的主要问题似乎是在您的第二个数据集中为您可以加入的产品找到一个列。目前尚不清楚您如何准确地决定 df_b 中各种产品列中的哪些值用作查找的键,而不是那些被忽略的键。

    不过,假设您的 df_a 包含一个详尽的产品值列表,并且这些值中的每一个仅在您可以执行此类操作时才连续出现(简化您的示例):

    import pandas as pd
    
    df_a = pd.DataFrame({'Region':['USA', 'Canada'], 'Product': ['apple', 'banana']})
    df_b = pd.DataFrame({'product1': ['apple', 'xyz'], 'product2': ['xyz', 'banana']})
    
    product_cols = ['product1', 'product2']
    
    df_b['Product'] = df_b[product_cols].apply(lambda x: x[x.isin(df_a.Product)][0], axis=1)
    df_b = df_b.merge(df_a, on='Product')
    

    这里最重要的是生成一个列,您可以加入该列进行查找

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2019-05-28
      • 2019-03-28
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-12-08
      相关资源
      最近更新 更多