if循环在返回后没有结束

时间:2020-03-18 01:27:01

标签: python loops if-statement

会员

我好几个小时都无法忍受,为什么我的代码无法正常工作。

我正在从CSV文件中获取数据,并且试图在两个代码匹配时更改一个值。

def mode(x):
for line in data_df['Bar_Code']:
    #print(line) ~ Line outputs the Barcodes in the Bar_Code Column of the CSV file.
    with open("Barcodes_to_match.txt") as barcodes:
        for barcode in barcodes:
            #print(barcode) ~ Outputs the Barcode that it need to be matched.
            if barcode == line:
                x = x.replace("True", "False")
                return x

data_df['Published'] = data_df['Published'].apply(lambda x: mode(x))

data_df.to_csv(('Products.csv'), encoding='UTF-8', quoting=csv.QUOTE_ALL, quotechar='"', index=None, sep=str(","))

Product.csv文件:

Bar_Code, Product, Published
BLA00BLA00, Product1, True
BLU00BLU00, Product2, False
BLI00BLI00, Product3, True
BLE00BLE00, Product4, False

Barcodes_to_match.txt:

BLA00BLA00
BLI00BLI00

因此,我需要将产品行(BLA00BLA00和BLI00BLI00)已发布列的值更改为 False

有人可以检查我的替换值的方法吗?

谢谢!

编辑: 当我添加打印命令时,似乎代码无休止地存储在最后一场比赛中。

if barcode == line:
   print(barcode + " = " + line)
   x = x.replace("True", "False")
   return x

Output:
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00
BLI00BLI00 = BLI00BLI00

1 个答案:

答案 0 :(得分:0)

我无法运行您的代码,要实现所需的功能,请尝试以下操作:

Always on

Products.csv

import csv
import pandas as pd

data_df = pd.read_csv('Products.csv')
print(data_df)

with open("Barcodes_to_match.txt") as f:
    barcodes = f.read().splitlines()

data_df.loc[data_df['Bar_Code'].isin(barcodes), 'Published'] = False

print(data_df)

data_df.to_csv(('Products.csv'), encoding='UTF-8', quoting=csv.QUOTE_ALL, quotechar='"', index=None, sep=str(","))