简体   繁体   English

如何从从 excel 文件派生的大量字典中的值列表中查找最小值和最大值

[英]How to find min and max values from list of values in large set of dictionary derived from excel file

I am new with dealing dictionary and Pandas in Python.我是处理字典和 Python 中的 Pandas 的新手。 I have a excel file with columns named sensor and values, sensors can be duplicates also, but their values can differ.我有一个 excel 文件,其中包含名为传感器和值的列,传感器也可以重复,但它们的值可能不同。 I converted them into dictionary merging duplicate sensors with their values.我将它们转换为字典,将重复的传感器与其值合并。 Now, I have a dictionary with sensors and their values as list (example given below).现在,我有一个字典,其中包含传感器及其值作为列表(下面给出示例)。 I want to return all the keys with the lowest and highest value from their list of values.我想从它们的值列表中返回所有具有最低和最高值的键。 Values can be duplicate also.值也可以重复。

{'Sensor1': [0.427, 0.13, 0.129, 0.124], 'sensor2': [2.376, 2.376, 0.712, 0.618.208, 0.133], 'sensor3': [0.21, 0.139], 'sensor4': [0.237, 0.123], 'sensor5': [0.997, 0.806, 6.78]}

I want the output to be我希望 output 成为

sensor1 0.124 0.427
sensor2 0.133 2.376
sensor3 0.139 0.21
.
.
.

The code that I have tried is giving me only first set of key,value pair ie我尝试过的代码只给了我第一组键值对,即

senor1 0.124 0.427

code -代码 -

df = pd.read_excel("sensor.xlsx")
a=df.set_index('sensor')['values'].to_dict()
b={k: g["values"].to_list() for k,g in df.groupby("sensor")}
for k,v in b.items():
    _max, _min = max(v), min(v)
    print(k, " ", _min, " ",  _max)

My excel file is large and this code is not working for that.我的 excel 文件很大,此代码不适用于此。 Please help, Thanks in Advance!请帮助,在此先感谢!

In you already have the dictionary then you can just load the data into the dataframe and evaluate min/max across axis = 1 .如果您已经有了字典,那么您可以将数据加载到 dataframe 并评估跨axis = 1min/max

data = {'Sensor1': [0.427, 0.13, 0.129, 0.124], 'sensor2': [2.376, 2.376, 0.712, 0.618208, 0.133], 'sensor3': [0.21, 0.139], 'sensor4': [0.237, 0.123], 'sensor5': [0.997, 0.806, 6.78]}

df = pd.DataFrame.from_dict(data, orient='index') 
df = pd.concat([df.min(1) , df.max(1)], axis =1)

Or you can use:或者您可以使用:

df = df.agg(['min', 'max'], axis='columns')  # suggested by @Cyttorak 

OUTPUT OUTPUT

            0      1
Sensor1  0.124  0.427
sensor2  0.133  2.376
sensor3  0.139  0.210
sensor4  0.123  0.237
sensor5  0.806  6.780

If you want to convert the above output back to dict :如果要将上述 output 转换回dict

result = df.T.to_dict('list')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM