【问题标题】:How do you order row values from an Excel file in Python with a dictionary?如何使用字典从 Python 中的 Excel 文件中排序行值?
【发布时间】:2021-12-30 15:54:13
【问题描述】:

假设我有一个 2 行的 excel 表:

0.296178    0.434362    0.033033    0.758968
0.559323    0.455792    0.780323    0.770423

如何使用字典将每行的值按从高到低的顺序排列?

例如,第 1 行的字典输入应如下所示:{1:[4,2,1,3]},因为第 1 行中的第 4 个值最高,第 1 行中的第 3 个值最低。

(不是从 0 开始索引,因为它是 Excel 文件)

【问题讨论】:

    标签: python excel dictionary


    【解决方案1】:

    为此,首先,您需要一个模块来导入 excel 文件。我推荐 pandas,因为它被广泛使用。 (如果没有,请使用“pip install pandas”安装它)

    之后使用此代码:

    import pandas as pd
    path = r'C:\Users\tanuj\Desktop\temp.xlsx' # replace it with your file path
    df = pd.read_excel(path, header = None)
    df.head() # to visualise the file
    
    #And then, use this simple logic to get the required dictionary
    d = {}
    for x in range(df.shape[0]):
        temp = {}
        values = list(df.iloc[x])
        for y in range(len(values)):
            temp[df.loc[x][y]] = y+1
        l = []
        for t in sorted(temp):
            l.append(temp[t])
        l.reverse()
        d[x+1] = l
    print(d)
    

    【讨论】:

      【解决方案2】:
      numpy 中的

      argsort 函数可以解决问题。考虑这段代码:

      import numpy as np
      import pandas as pd
      
      df = pd.read_csv('excel.csv', delimiter=',', header=None)
      
      i = 0
      dict = {}
      for row in df.values:
          arg = np.argsort(row)
          iarg = list(map(lambda x: x+1, arg))
          iarg.reverse()
          dict[i]=iarg
          i = i + 1
      
      print(dict)
      

      它将输入数据读取为格式化的 csv,并为您提供所需的输出。

      【讨论】:

        【解决方案3】:

        在阅读完您的问题后,我认为您想从 Excel 工作表中读取行值并将其存储在字典中,然后希望将字典中的值从最高到最低顺序排序...

        所以首先您必须读取存储此类值的 excel 文件以供您使用 openpyxl module

        from openpyxl import load_workbook
        wb = load_workbook("values.xlsx")  
        ws = wb['Sheet1']
        for row in ws.iter_rows():
            print([cell.value for cell in row])
        

        上面的代码将生成excel文件中的值列表

        在你的情况下:

        [0.296178, 0.434362, 0.033033, 0.758968] [0.559323, 0.455792, 0.780323, 0.770423]

        现在您必须将其存储在字典中,然后对其进行排序...

        from openpyxl import load_workbook
        
        wb = load_workbook("values.xlsx")  
        ws = wb['Sheet1']
        
        value_dict={}
        n=1
        #extracting value from excel
        for row in ws.iter_rows():  
            values=[cell.value for cell in row]
            value_dict[n]=values
            n=n+1
        
        print(value_dict)
        
        #Sorting Values
        for keys,values in value_dict.items():
            values.sort(reverse=True)
            print("Row "+ str(keys),values)
        

        以上代码执行您想要执行的相同任务...

        Output Image

        【讨论】:

          【解决方案4】:

          对于 df 中的每一行,您可以将每个元素与该行的排序版本进行比较并获取索引。

          import pandas as pd
          
          
          a = [0.296178,    0.434362,    0.033033,    0.758968]
          b = [0.559323,    0.455792,    0.780323,    0.770423]
          df = pd.DataFrame(columns = ['1', '2'], data = zip(a, b)).T
          
          
          def compare_sort(x):
            x = list(x)
            y = sorted(x.copy())[::-1]
            return([x.index(y[count]) +1 for count, _ in enumerate(y) ])
          
          
          
          print(df.apply(compare_sort, axis=1)) # apply func. to each row of df  
          
          1    [4, 2, 1, 3]
          2    [3, 4, 1, 2]
          
          # Get data by row name
          
          df = df.apply(compare_sort, axis=1)
          print(df['1'])
          
          [4, 2, 1, 3]
          

          有用的链接。

          get-indices-of-items

          reverse-a-list

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-03-18
            • 1970-01-01
            • 2019-09-21
            • 2023-04-10
            • 2014-11-10
            • 2017-06-24
            • 2021-05-08
            相关资源
            最近更新 更多