【发布时间】: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是您想要查找的产品,而您显然在同一行中有其他产品但您忽略了。