【问题标题】:Find missing dataframe elements not present in a given input list查找给定输入列表中不存在的缺失数据框元素
【发布时间】:2020-09-28 16:10:02
【问题描述】:

有一个用户定义的列表values = ['color','oilType','motor'] 和一个数据框 df,它有 15 列,包括“颜色”和 14 个其他列名。 df 中不存在“oilType”和“motor”。但是,在运行以下 sn-p 时,仅输出“电机”。理想的输出(df 中缺少的列)应该是 'oilType' 和 'motor'

df = pd.read_csv('type.csv',sep=',',error_bad_lines=False)
targets=list(df.columns)
values = ['color','oilType','motor']
with open("source.txt", "w") as output:
    output.write(str(values))
with open('source.txt','r') as source:
    for source1 in values:
        source1 = source1.strip().lower()
    for target1 in targets:
        if source1 not in target1:
            with open("columns_missing.txt", "w") as output:
                output.write(str(source1))

应该改变什么,以便在 df 中发现 'oilType' 和 'motor' 都缺失

【问题讨论】:

    标签: python-3.x pandas list dataframe


    【解决方案1】:

    你的 for 循环应该是嵌套的,而不是嵌套的。当您迭代values 时,您没有对每个值做任何事情,您只是以“电机”结束。因此,当您开始迭代 targets 时,您的 source1 变量是“电机”并且不会改变。尝试像这样缩进:

    df = pd.read_csv('type.csv',sep=',',error_bad_lines=False)
    targets=list(df.columns)
    values = ['color','oilType','motor']
    with open("source.txt", "w") as output:
        output.write(str(values))
    with open('source.txt','r') as source:
        for source1 in values:
            source1 = source1.strip().lower()
            for target1 in targets:
                if source1 not in target1:
                    with open("columns_missing.txt", "w") as output:
                        output.write(str(source1))
    

    一般来说,处理您正在做的事情的更好方法是使用集合的difference 方法:

    data = np.random.randint(50, size=20).reshape(5,4)
    df = pd.DataFrame(data, columns=["A", "B", "C", "D"])
    
    print(df)
        A   B   C   D
    0  28  40  29  44
    1  29   7  48  38
    2  41   5  48  31
    3  45  42  28  44
    4   6  45  15  37
    
    values = ["hello", "B", "world", "D"]
    not_found = set(values).difference(df.columns)
    print(not_found) # not_found == {"hello", "world"}
    
    with open("columns_missing.txt", "w") as output:
        for value in not_found:
            output.write(value)
    

    【讨论】:

    • 一套差法跑得很好..非常感谢
    猜你喜欢
    • 2018-04-20
    • 1970-01-01
    • 2011-07-12
    • 2019-10-11
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    相关资源
    最近更新 更多