python - 如何修复 flake 8 错误 "E712 comparison to False should be ' 如果 cond 为 False :' or ' 如果不是 cond :'"在 pandas dataframe

标签 python pandas pep8 flake8

我在行“added_pa​​rts = new_part_set[(new_part_set["duplicate"] == False) & (new_part_set["version"] == "target")]"**

以下是我们用于电子表格比较的代码片段

source_df = pd.read_excel(self.source, sheet).fillna('NA')
target_df = pd.read_excel(self.target, sheet).fillna('NA')
file_path = os.path.dirname(self.source)

column_list = source_df.columns.tolist()

source_df['version'] = "source"
target_df['version'] = "target"

source_df.sort_values(by=unique_col)
source_df = source_df.reindex()
target_df.sort_values(by=unique_col)
target_df = target_df.reindex()

# full_set = pd.concat([source_df, target_df], ignore_index=True)
diff_panel = pd.concat([source_df, target_df],
                       axis='columns', keys=['df1', 'df2'], join='outer', sort=False)
diff_output = diff_panel.apply(self.__report_diff, axis=0)
diff_output['has_change'] = diff_output.apply(self.__has_change)

full_set = pd.concat([source_df, target_df], ignore_index=True)
changes = full_set.drop_duplicates(subset=column_list, keep='last')
dupe_records = changes.set_index(unique_col).index.unique()

changes['duplicate'] = changes[unique_col].isin(dupe_records)
removed_parts = changes[(changes["duplicate"] == False) & (changes["version"] == "source")]
new_part_set = full_set.drop_duplicates(subset=column_list, keep='last')
new_part_set['duplicate'] = new_part_set[unique_col].isin(dupe_records)
added_parts = new_part_set[(new_part_set["duplicate"] == False) & (new_part_set["version"] == "target")]

diff_file = file_path + "file_diff.xlsx"
if os.path.exists(diff_file):
    os.remove(diff_file)
writer = pd.ExcelWriter(file_path + "file_diff.xlsx")
diff_output.to_excel(writer, "changed")
removed_parts.to_excel(writer, "removed", index=False, columns=column_list)
added_parts.to_excel(writer, "added", index=False, columns=column_list)
writer.save()

是否有任何其他方法可以避免这种情况,不确定是否要进一步进行。

最佳答案

在您的 DataFrame 掩码中,您有 (changes["duplicate"] == False)(new_part_set["duplicate"] == False) flake8 建议你应该改变这些。它提示的原因是在 python 中,使用 == 运算符比较 bool 值被认为是不好的做法,而你应该写 if my_bool:...if not my_bool:... 等。在 pandas 中,如果你有一个 bool 系列,你可以使用 ~ 运算符对其取反,这样你的新掩码将被写入:

~changes["duplicate"] # & ... blah blah
~new_part_set["duplicate"] # & ... blah blah

关于python - 如何修复 flake 8 错误 "E712 comparison to False should be ' 如果 cond 为 False :' or ' 如果不是 cond :'"在 pandas dataframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54474042/

相关文章:

javascript - 为什么在 JavaScript 中收到我的个人推文 ID 号时,最后几位数字变为 "0"?

python - 指纹识别系统

python - 我如何获得 Pandas 的年龄和日期

python - 迭代数据帧时所做的更改不会保存

python - PEP 8 是否需要函数参数中的运算符周围有空格?

python - 有没有更好的方法将此 Python/Django 代码格式化为有效的 PEP8?

python - Pep8 E501 : line too long error

python - 如何获取 Python/Google 应用引擎中的键名列表?

python - 为什么生成器更快?

python - 将预定义的数字分配给数据框中的列行值