Python-比较列值和行值

时间:2019-01-09 02:07:59

标签: python-3.x pandas dataframe

目前存在一些逻辑问题...基本上,我正在尝试将一个CSV的列值与另一个CSV的行值进行比较。到目前为止,这是我的代码:

import tkinter as tk
from tkinter import filedialog

#import numpy as np
#import matplotlib.pyplot as plt
import pandas as pd

root = tk.Tk()
root.withdraw()

thresholdsFile = filedialog.askopenfilename(title='Select The Thresholds File:')
mDataFile = filedialog.askopenfilename(title='Select The M Data File:')

df = pd.read_csv(thresholdsFile)
df2 = pd.read_csv(mDataFile)

def thresholdCheck(thresholds, mdata):
    for index, row in thresholds.iterrows():
        for index1, row1 in mdata.iterrows():
            if (row1[index1]) < row['Minimum Threshold:']:
                print('Minimum threshold broken!')
            elif (row1[index1]) > row['Maximum Threshold:']:
                print('Maximum threshold broken!')
            else:
                print('No threshold broken!')

sampleOutput = thresholdCheck(df, df2)
print(sampleOutput)

它产生以下输出:

最小阈值已损坏! 最高阈值破了! 没有门槛被打破! 最高阈值破了! 没有

错了。 :(

我随附了两个示例CSV,用于测试代码。ThresholdsMachine Data

所以它应该工作的方式是应该以垂直方式读取2机器数据的列值,并将其与阈值数据的水平行1进行比较,因此在这种情况下应该像这样:

(油温)55与56和115(第一张图中的最小/最大阈值)进行比较,触发器低于56 --->最小阈值被破坏

将(油温)116与56和115(最小/最大阈值)进行比较,触发超过115 --->打破最大阈值

现在

(压油)43与44和126(最小/最大阈值)进行比较,触发低于44 --->最小阈值被破坏

(压油)127与44和126(最小/最大阈值)进行比较,触发超过126 --->打破最大阈值

输入

df = pd.DataFrame( {'Variable Name:':['Oil Temp','Oil Press'],
                    'Minimum Threshold:':[56,44],'Maximum Threshold:':[115, 126]})

df2 = pd.DataFrame({'Oil Temp':[95,116],'Oil Press':[43,127]})

1 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

## set index, easy to look up
df1 = df1.set_index('Variable Name')

# convert to dict
df2_dict = df2.to_dict(orient='list')

result = []

for k,v in df2_dict.items():
    vals = df1.loc[k].tolist()
    for j in v:

        if j < min(vals):
            result.append('minimum threshold broken')

        if j > max(vals):
            result.append('maximum threshold broken')

print(result)

['minimum threshold broken',
 'maximum threshold broken',
 'minimum threshold broken',
 'maximum threshold broken']

设置

df1 = pd.DataFrame({'Variable Name':['Oil Temp','Oil Press'],
                    'Minimum Threshold': [56, 44],
                    'Maximum Threshold': [115, 126]})

df2 = pd.DataFrame({'Oil Temp':[55, 116],
                    'Oil Press': [43, 127]})