【问题标题】:pandas.dataframe to orderedDictionary: using a passed argument to specify the key column name instead of explicitly writing itpandas.dataframe 到 orderedDictionary:使用传递的参数来指定键列名称,而不是显式编写它
【发布时间】:2018-03-20 12:47:53
【问题描述】:

基于此answer 我想编写一个函数将csv 加载到OrderedDict() 中,但我不知道如何解决将键列名称作为字符串传递而不是手动声明它?这是我的代码,它会更清楚:

dic_key = 'uniqueID'
df.dic_key #this gives AttributeError: 'DataFrame' object has no attribute 'dic_key'

而不是df.uniqueID,其中uniqueID 是我们想要将其用作键的列的名称

这里是完整的代码:

def csv_to_OrderedDic1(path, dic_key='uniqueID'):
    '''

    Parameters:
        dic_key: the name of the column to be used as the dictionary key

    '''
    df = pd.DataFrame.from_csv(path, sep='\t', header=0)
    # Get an unordered dictionary
    unordered_dict = df.set_index(dic_key).T.to_dict('list')
    # Then order it
    ordered_dict = OrderedDict((k,unordered_dict.get(k)) for k in df.dic_key)
    return ordered_dict

【问题讨论】:

    标签: python pandas dictionary dataframe ordereddictionary


    【解决方案1】:

    我认为更好的是使用read_csv 和选择列[] 而不是点符号:

    def csv_to_OrderedDic1(path, dic_key='uniqueID'):
        '''
    
        Parameters:
            dic_key: the name of the column to be used as the dictionary key
    
        '''
        df = pd.read_csv(path, sep='\t', header=0)
        # Get an unordered dictionary
        unordered_dict = df.set_index(dic_key).T.to_dict('list')
        # Then order it
        ordered_dict = OrderedDict((k,unordered_dict.get(k)) for k in df[dic_key])
        return ordered_dict
    

    使用zip 并删除drop 的列的另一种解决方案:

    def csv_to_OrderedDic1(path, dic_key='uniqueID'):
        '''
    
        Parameters:
            dic_key: the name of the column to be used as the dictionary key
    
        '''
        df = pd.read_csv(path, sep='\t', header=0)
        L = zip(df[dic_key], df.drop(dic_key, 1).values.tolist())
        ordered_dict = OrderedDict(L)
        return ordered_dict
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2013-04-17
      • 2013-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      相关资源
      最近更新 更多